【问题标题】:angular 7 & spring boot 2 file upload problemangular 7 & spring boot 2 文件上传问题
【发布时间】:2020-04-19 23:01:38
【问题描述】:

文件上传.html

    <p-fileUpload name="file" customUpload="true" (uploadHandler)="myUploader($event)"
 type="file" accept=".lsx, .xlsx" [auto]="true" ></p-fileUpload>

文件上传.ts

    myUploader(event):void{

        const formdata:FormData = new FormData();
        const fileToUpload: File = event.files[0];

        formdata.append('file', fileToUpload);

        const req = new HttpRequest('POST', 'http://localhost:8081/fileUpload', formdata);

       this.httpClient.request(req).subscribe(); 
}

文件上传.java

   @PostMapping(value = "/fileUpload")
    public ApiResponse giftCardBatchList(@RequestParam("file") MultipartFile file) {
        fileUploadService.upload(file);
        return new ApiResponse(ApiResponseStatus.SUCCESS, null);
    }

控制器没有捕捉到请求,我得到了这个异常

MissingServletRequestPartException:所需的请求部分“文件”是 不存在

如果我改变了

@RequestParam("file") MultipartFile 文件

@RequestParam("file") MultipartFile[] 文件

控制器捕获请求,但文件数组不包含任何内容。它是空的:(

有什么想法吗?

谢谢你们!

【问题讨论】:

  • 试试这种方式@RequestParam MultipartFile file 告诉我。
  • 得到了同样的异常“所需的请求部分'文件'不存在”:(
  • 尝试在请求的标头中传递内容类型,像这样。new HttpRequest('POST', 'http://localhost:8081/fileUpload', formData, {headers: headers}); 参考这个stackoverflow.com/questions/48279484/…
  • 我用相同的标头做了完全相同的请求,但得到了相同的异常:(

标签: java angular spring upload


【解决方案1】:

尝试如下修改注释,

@PostMapping(value = "/fileUpload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public ApiResponse giftCardBatchList(@RequestParam(value = "file") MultipartFile file) {
        fileUploadService.upload(file);
        return new ApiResponse(ApiResponseStatus.SUCCESS, null);
    }

【讨论】:

  • 没用 :( 得到相同的异常 所需的请求部分“文件”不存在
  • 您能否检查您的请求负载是否已提交文件?
  • 将此添加到您的 application.properties,# Enable multipart uploads spring.servlet.multipart.enabled=true # Threshold after which files are written to disk. spring.servlet.multipart.file-size-threshold=2KB # Max file size. spring.servlet.multipart.max-file-size=200MB # Max Request Size spring.servlet.multipart.max-request-size=215MB
  • 对这些属性没有帮助:(
【解决方案2】:

在调用post api之前尝试如下修改ts文件

const formdata: FormData = new FormData(); const headers = new HttpHeaders().set('Content-Type','application/json');

formdata.append("file",fil[0]);

或 formdata.set("文件",fil[0]);

【讨论】:

  • 在这些更改之后我得到了同样的异常:(
猜你喜欢
  • 2017-12-30
  • 1970-01-01
  • 1970-01-01
  • 2017-04-13
  • 2019-09-23
  • 2020-11-28
  • 2023-04-01
  • 2019-06-25
  • 2021-06-09
相关资源
最近更新 更多