Java 尝试使用 ng-file-upload 在 Spring 中上传许多文件时出现 Empty List<MultipartFile>

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35160483/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 16:23:20  来源:igfitidea点击:

Empty List<MultipartFile> when trying to upload many files in Spring with ng-file-upload

javaangularjsspringspring-mvcng-file-upload

提问by fracz

I have the following controller method for uploading multiple files at once, inspired by this blog postand answers to this questionas well:

我有以下控制器方法可以一次上传多个文件,灵感来自这篇博客文章这个问题的答案:

@RequestMapping(value = "/{user}/attachment", method = RequestMethod.POST)
@PreAuthorize(...)
public void upload(@PathVariable User user, 
                   @RequestParam("file") List<MultipartFile> files) {
  // handle files
}

However, the list of the files is always empty although request contains them.

但是,尽管请求包含文件,但文件列表始终为空。

If I add the third MultipartRequestparameter to the method:

如果我将第三个MultipartRequest参数添加到方法中:

public void upload(@PathVariable User user, 
                   @RequestParam("file") List<MultipartFile> files,
                   MultipartRequest request)

I can see it contains my uploaded files correctly:

我可以看到它正确包含我上传的文件:

request contents

请求内容

What might be the reason of empty List<MultipartFile>?

空的原因可能是什么List<MultipartFile>

I'm using ng-file-uploadto submit the files, but I don't think it is connected with the issue. Spring 4.2.4.

我正在使用ng-file-upload提交文件,但我认为它与问题无关。春天 4.2.4。

采纳答案by fracz

The problem was that ng-file-uploadby default submits array of files using names file[0], file[1]etc. It is configurable with the arrayKeyvalue when using UploadService. Setting it to empty string forces the files to be sent under the same filekey, which is correctly resolved with Spring and the @RequestParam("file") List<MultipartFile>contains all files that has been submitted.

问题是,NG-文件上传的文件默认的提交阵列使用的名字file[0]file[1]等,这是可配置的arrayKey使用,当值Upload服务。将其设置为空字符串会强制使用相同的file密钥发送文件,这在 Spring 中得到了正确解析,并且@RequestParam("file") List<MultipartFile>包含所有已提交的文件。

Upload.upload({url: url, data: {file: arrayOfFiles}, arrayKey: ''})

回答by Abdelhak

Try to use @ModelAttributelike this:

尝试@ModelAttribute像这样使用 :

    @RequestMapping(value = "/{user}/attachment", method = RequestMethod.POST)
    @PreAuthorize(...) 
    public void upload(@PathVariable User user,@ModelAttribute("uploadFile") FileUpload uploadFile) throws IllegalStateException, IOException {

    List<MultipartFile> files = uploadFile.getFiles();
    ...

And create a class like:

并创建一个类,如:

     public class FileUpload {
     private List<MultipartFile> files;
     public List<MultipartFile> getFiles() {
        return files;
     }

    public void setFiles(List<MultipartFile> files) {
       this.files= files;
      }
   }

回答by alexandrum

I think that in the way you sent data from front, it can not boundwith java.util.List. If you create a JSON data as request and you annotated your List with @RequestBody like:

我认为在您从前面发送数据的方式中,它不能与 java.util.List绑定。如果您创建一个 JSON 数据作为请求并使用 @RequestBody 注释您的列表,例如:

@RequestMapping(value = "/{user}/attachment", method = RequestMethod.POST)
@PreAuthorize(...)
public void upload(@PathVariable User user, 
                   @RequestBody List<MultipartFile> files) {
  // handle files
}

this should work. Some info here.

这应该有效。一些信息在这里

回答by Dmitri Algazin

That works for me, sending big 'email' object with multiple file attachments from UI to back-end:

这对我有用,将带有多个文件附件的大“电子邮件”对象从 UI 发送到后端:

Angular

sendEmailWithAttachments(taskId: string, template: string, email: any, modelConfig: any, files: any[]) {
    let formData = new FormData();
    formData.append('form', new Blob([JSON.stringify(email)], {type: 'application/json'}));
    files.forEach(file  => {
        formData.append('files', file);
    });

    return this.$http({
        method: 'POST',
        data: formData,
        url: this.baseUrl + '/' + taskId + '/email-with-attachment?template=' + template,
        headers: {
            'Content-Type': undefined
        },
        responseType: 'arraybuffer'
    });
}

Java Spring

Java 春天

@RequestMapping(value = "{taskId}/email-with-attachment", method = RequestMethod.POST, consumes = MULTIPART_FORM_DATA_VALUE)
public void sendEmailWithAttachment(
        @PathVariable String taskId,
        @RequestParam String template,
        @RequestParam("form") MultipartFile form,
        @RequestParam("files") List<MultipartFile> files) throws IOException {
    Map<String, String> parameters = new ObjectMapper().readValue(form.getInputStream(), HashMap.class);

    System.out.println("taskId", taskId);
    System.out.println("template", template);
    System.out.println("files", files);
    System.out.println("parameters", parameters);
}