天天看点

angularjs上传文件+jfinal接收上传文件

准备js插件:angular-file-upload.min.js

jsp部分:

<input  type="file" nv-file-select="" uploader="uploader"/>

<input  type="button" value="上传补丁"  ng-click="uploadFile()"/>

angularjs部分:

var myApp = angular.module("myApp", ["angularFileUpload"]);

myApp.controller('patchList', [ '$scope', 'FileUploader',

  function($scope, FileUploader) {

   var uploader = $scope.uploader = new FileUploader({

    // 访问java方法的http请求

    url : ctx + '/patch/uploadPatch'

   });

//上传完成之后的回调方法,还有很多类似方法,此处不一一列举

 uploader.onCompleteItem = function(fileItem, response, status, headers) {

    //上传成功之后你要调用的angularjs方法    

   $scope.getPatchList();

   };

   $scope.uploadFile = function() {

    console.log("上传文件啦....");

    uploader.uploadAll();

   }

  } ]);

java部分:

 public void uploadPatch(){

  System.out.println("接收到上传文件啦.....");

  UploadFile uploadFile=this.getFile();

  File file=uploadFile.getFile();

  String fileName=uploadFile.getOriginalFileName();

  //PatchConstant.PATCH_UPLOAD_PATH自定义文件存储的路径

  File newFile=new File(PatchConstant.PATCH_UPLOAD_PATH+fileName);

  try {

   newFile.createNewFile();

  } catch (IOException e) {

   e.printStackTrace();

  }

 //将上传文件写入到本地文件

  ToolFile.fileChannelCopy(file,newFile);   

 }

public static void fileChannelCopy(File s, File t) {

        FileInputStream fi = null;

        FileOutputStream fo = null;

        FileChannel in = null;

        FileChannel out = null;

        try {

            fi = new FileInputStream(s);

            fo = new FileOutputStream(t);

            in = fi.getChannel();// 得到对应的文件通道

           out = fo.getChannel();// 得到对应的文件通道

            in.transferTo(0, in.size(), out);// 连接两个通道,并且从in通道读取,然后写入out通道

        } catch (IOException e) {

            e.printStackTrace();

        } finally {

            try {

                fi.close();

                in.close();

                fo.close();

                out.close();

            } catch (IOException e) {

                e.printStackTrace();

            }

        }

    }

jfinal实现接收上传文件参考资源:http://www.cnblogs.com/acehalo/p/3915720.html

angular-file-upload官方网站:https://github.com/nervgh/angular-file-upload

(官方实例位于angular-file-upload-master/angular-file-upload-master/examples中)

继续阅读