【问题标题】:Accepting List<MultipartFile> files from Angular接受来自 Angular 的 List<MultipartFile> 文件
【发布时间】:2019-06-02 04:13:45
【问题描述】:

我在将多个文件从 angular 前端发送到 spring-boot 后端时遇到问题。我已经尝试了堆栈和网络中的所有内容,但我找不到答案。这是我的代码:

角度: .ts 文件:

  submit(){
    this.uploadedFiles = this.uploadedFiles.map(item => {
      let formData = new FormData();
      return formData.append('file',item,item.name);
    });
    this.service.postFile(this.uploadedFiles).subscribe(result => {
      console.log(result);
    })
  }

this.uploadedFiles 以某种方式未定义 FormData 类型?

服务文件:

postFile(files: any): Observable<string>{
      return this.http.post('/id/file', files, {responseType:'text'});
  }

弹簧控制器:

    @PostMapping(value = "/file")
private String newFile(@RequestBody List<MultipartFile> mf) {
    return "error";
}

在调试器内部,mf 列表为 null。

主要问题是对于 1 个文件(当我只使用 MultipartFile 时),我的代码可以正常工作。

我正在使用 PrimeNG 的 p-fileupload 和自定义上传事件。

【问题讨论】:

    标签: angular spring file-upload


    【解决方案1】:

    我认为问题在于您将FormData 实例的数组发送到postFile,因为您在map 内一次又一次地实例化formData

    试试看是否可行:

    submit() {
      const formData = new FormData();
      this.uploadedFiles = this.uploadedFiles.map(item => formData.append('file', item, item.name));
      this.service.postFile(this.uploadedFiles).subscribe(result => console.log(result));
    }
    

    PS:我没有对此进行测试,但我觉得它应该可以工作。

    更新:

    我认为您正在将 formData 记录到控制台,如下所示:

    console.log(files);
    

    在您的 postFile 方法中。

    或者:

    console.log(formData);
    

    在您的组件中。

    你应该做的是

    console.log(formData.get('file'));
    

    【讨论】:

    • 它也返回未定义
    • 我已经按照你说的那样尝试过了,我得到了 2 个文件,2 个包含名称、lastModified、类型的文件对象...
    • 是的,我的意思是对于两个选定的文件,它将在一个数组中显示两个文件对象。你到底期待什么?
    猜你喜欢
    • 1970-01-01
    • 2018-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-03
    • 1970-01-01
    • 2020-06-02
    • 1970-01-01
    相关资源
    最近更新 更多