简体   繁体   English

Spring MVC从AngularJs上传文件

[英]Spring MVC Upload File from AngularJs

i did the part AngularsJs of the file upload and when i tried to send the uploaded file to my controller i got an error that the url not valid: 我做了文件上传的AngularsJs部分,当我尝试将上传的文件发送到我的控制器时,我收到一个错误,指出网址无效:

My controller is: 我的控制器是:

@RestController
@RequestMapping("/files")
public class UploadController {
@RequestMapping(value = "/fileUpload", method = RequestMethod.POST)
    @Produces(MediaType.APPLICATION_JSON) 
    public Data continueFileUpload(HttpServletRequest request, HttpServletResponse response){
            MultipartHttpServletRequest mRequest;

....

}

the Service AngularJs that link the controller is: 链接控制器的Service AngularJs为:

controller JS function: 控制器JS功能:

$scope.uploadFile = function() {
        var file = $scope.myFile;
        console.log('file is ');
        console.dir(file);

        var uploadUrl = "/fileUpload";  /*i need here to know which url i must set*/
        FileUploadService.uploadFileToUrl(file, uploadUrl).then(
                function(result) {
                    $scope.errors = FileUploadService.getResponse();
                    console.log($scope.errors);
                    $scope.errVisibility = true;
                }, function(error) {
                    alert('error');
                })

    }

The FileUploadService js: FileUploadService js:

myapp.service('FileUploadService', [ '$q', '$http', function($q, $http) {
    var deffered = $q.defer();
    var responseData;
    this.uploadFileToUrl = function(file, uploadUrl) {
        var fd = new FormData();
        fd.append('file', file);
        return $http.post(uploadUrl, fd, {
            transformRequest : angular.identity,
            headers : {
                'Content-Type' : undefined
            }
        }).success(function(response) {

            /* $scope.errors = response.data.value; */
            console.log(response);
            responseData = response;
            deffered.resolve(response);
            return deffered.promise;
        }).error(function(error) {
            deffered.reject(error);
            return deffered.promise;
        });

    }

    this.getResponse = function() {
        return responseData;
    }

} ]);

I wonder which URl i must pass in order to call the continueFileUpload? 我想知道我必须通过哪个URl才能调用continueFileUpload?

Updated: 更新:

控制器Java

the itr is loaded empty itr加载为空

the directive i used is : 我使用的指令是:

文件上传指令

the html : 的html:

html文件上传

试试:var uploadUrl =“ / files / fileUpload”;

try to use like below 尝试使用如下

maven web project Maven Web项目

var uploadUrl = "./fileUpload";

normal webproject 普通的Web项目

var uploadUrl = "../fileUpload";

or you directly call with below format 或者您直接使用以下格式致电

http://yourip:portnumber/projectName/controllerName;

i hope it will working fine 我希望它能正常工作

This is the full working solution: 这是完整的工作解决方案:

controller.java: controller.java:

@RestController
@RequestMapping("/api")
public class FileController {
    @RequestMapping(value = "/getFile", method = RequestMethod.POST)
        public ResponseEntity<byte[]> getFileForm(@RequestParam(value = "file") MultipartFile multipartFile)
                throws IOException {

            // code ............
            return null;

        }}

Angular.Js: Angular.js:

$scope.downloadFile = function(){

              var a = document.createElement("a");
              document.body.appendChild(a);
              var fileExt = $scope.file.name.substring($scope.file.name.lastIndexOf('.')+1, $scope.file.namee.length) || $scope.file.name;

             var fileType = FileService.GenerateFileType(fileExt);

              FileService.getFile($scope.file).success(function(data){

                    var file = new Blob([data], {type:fileType});
                    var fileURL = window.URL.createObjectURL(file);
                    a.href = fileURL;
                    a.download = $scope.file.name;
                    a.click();


                });
}

FileService.js: FileService.js:

var GenerateFileType = function (fileExtension) {  
    var FileType = null;    
    switch (fileExtension.toLowerCase()) {  
            case "doc":  
            case "docx":  
                FileType = "application/msword";  
                break;  
            case "xls":  
            case "xlsx":  
                FileType = "application/vnd.ms-excel";  
                break;  
            case "pps":  
            case "ppt":
            case "pptx":
                FileType = "application/vnd.ms-powerpoint";  
                break;  
            case "txt":  
            case "properties":
                FileType = "text/plain";  
                break;  
            case "rtf":  
                FileType = "application/rtf";  
                break;  
            case "pdf":  
                FileType = "application/pdf";  
                break;  
            case "msg":  
            case "eml":  
                FileType = "application/vnd.ms-outlook";  
                break;  
            case "gif":  
            case "bmp":  
            case "png":  
            case "jpg":  
                FileType = "image/JPEG";  
                break;  
            case "dwg":  
                FileType = "application/acad";  
                break;  
            case "zip":  
                FileType = "application/x-zip-compressed";  
                break;  
            case "rar":  
                FileType = "application/x-rar-compressed";  
                break;  
        }  
    return FileType;
    }  

and

 var getFile = function(fileObj){

              return    $http({
                  method: 'POST',
                  url: "api/getFile",

                  headers: { 'Content-Type': undefined },

                  transformRequest: function (data) {
                      var fd = new FormData();
                      fd.append("file", data.file);

                    return fd;
                  },

                  data: {file: fileObj }
                });
             }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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