Spring MVC 在< MultipartFile>Spring中使用ng-file-upload上传多个文件时列表为空

qkf9rpyu  于 2023-01-21  发布在  Spring
关注(0)|答案(5)|浏览(135)

我有下面的控制器方法可以同时上传多个文件,它的灵感来自this blog post,也是对this question的回应:

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

但是,尽管request包含这些文件,但文件列表始终为空。
如果我在方法中添加第三个MultipartRequest参数:

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

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

List<MultipartFile>为空的原因可能是什么?
我使用ng-file-upload来提交文件,但我不认为它与问题有关。

icnyk63a

icnyk63a1#

问题是ng-file-upload默认使用名称file[0]file[1]等提交文件数组。在使用Upload服务时,可以使用arrayKey值进行配置。将其设置为空字符串将强制在相同的file键下发送文件,该键可以使用Spring正确解析,并且@RequestParam("file") List<MultipartFile>包含已提交的所有文件。

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

c0vxltue2#

尝试像这样使用@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();
    ...

并创建一个类,如下所示:

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

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

ztmd8pv53#

这对我很有效,从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

@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);
}
siv3szwd

siv3szwd4#

为多个文件.做这在你的javascript

//first add files to form data
var formData = new FormData();
for (let i = 0; i < files.length; i++) {
    formData.append("images", files[i]);
}

//post files to backend e.g using angular
 $http.post('upload', formData, {
     transformRequest: angular.identity,
     headers: {'Content-Type': undefined}
 })
 .then(function(response){
      console.log("UPLOAD COMPLETE::=> ", response);
 }, function (error) {
      console.log(error);
 });

在java中执行此操作

//your java method signature
@PostMapping(value = "/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE )
public Response uploadImage(@RequestParam(value = "images") MultipartFile[] images){

}
fzwojiic

fzwojiic5#

我认为从前端发送数据的方式,无法与java. util. List * a绑定**。如果创建JSON数据作为请求,并使用@RequestBody注解List,如:

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

这个应该行的一些信息here

相关问题