简体   繁体   中英

Drag Drop file upload with AngularJS and Spring Rest

I have angularjs And spring rest file upload it work well but i need to change file upload in html file to dropzone.js or any drag drop file upload,I tried dropzone.js library but I couldn't integrate it with angular ,Can any one help me how can i do that?

Angularjs controller

   $scope.document = {};
   $scope.setTitle = function(fileInput) {
   var file=fileInput.value;
   var filename = file.replace(/^.*[\\\/]/, '');
   var title = filename.substr(0, filename.lastIndexOf('.'));
   $("#title").val(title);
   $("#title").focus();
   $scope.document.title=title;
 };


 $scope.uploadFile=function(){
        var formData=new FormData();
        formData.append("file",file.files[0]);
        $http.post('/app/newDocument', formData, {
            transformRequest: function(data, headersGetterFunction) {
                return data;
            },
            headers: { 'Content-Type': undefined }
            }).success(function(data, status) {                       
                console.log("Success ... " + status);
            }).error(function(data, status) {
                console.log("Error ... " + status);
            });
  };
 });

html form

  <form ng-submit="uploadFile()" class="form-horizontal"
              enctype="multipart/form-data">
 <input type="file" name="file" ng-model="document.fileInput" id="file" />
 <input type="text" class="col-sm-4" ng-model="document.title" id="title" />
    </form>

Rest Controller

@RequestMapping(value="/newDocument", method = RequestMethod.POST)
    public void UploadFile(MultipartHttpServletRequest request,
   HttpServletResponse response) throws IOException {

        Attachment attachment=new Attachment();
        Iterator<String> itr=request.getFileNames();
        MultipartFile file=request.getFile(itr.next());
        String fileName=file.getOriginalFilename();
        attachment.setName(fileName);
        File dir = new File("D:\\file");
         if (dir.isDirectory())
         {
            File serverFile = new File(dir,fileName);
           BufferedOutputStream stream = new BufferedOutputStream(
                 new FileOutputStream(serverFile));
           stream.write(file.getBytes());
           stream.close();
       }else {
        System.out.println("not");
      }

 }

I would personally use a dedicated directive such as the excellent:

https://github.com/danialfarid/angular-file-upload https://github.com/flowjs/ng-flow

These take care of the boilerplate code and let you focus on styling and creating an upload service that works in sync with your API.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM