【问题标题】:Angular 8 Springboot File Upload hopelessAngular 8 Springboot 文件上传无望
【发布时间】:2020-06-09 03:37:18
【问题描述】:

谷歌“Angular 8 Springboot 文件上传”。我尝试了前 3 页。无法上传该死的文件。

我得到的最远的是:

已解决 [org.springframework.web.multipart.MultipartException: Current request is not a multipart request]

尽我所能。

我只想从 Angular 发送一个文件并在 spring boot rest 控制器中接收它。 有人可以帮我解决这个问题吗?

后端:

@PostMapping("/users/profile/upload")
@ResponseStatus(HttpStatus.OK)
public ResponseEntity<String> uploadData(@RequestParam("file") MultipartFile file)
        throws Exception {
    if (file == null) {
        throw new RuntimeException("You must select the a file for uploading");
    }
    String originalName = file.getName();

    // Do processing with uploaded file data in Service layer
    return new ResponseEntity<String>(originalName, HttpStatus.OK);
}

前端服务:

uploadFile(file: File): Observable<any> {

const formData = new FormData();

formData.append('file', file, 'file');
const headers = new HttpHeaders({
  'Content-Type': 'multipart/form-data'
});
const options = { headers };

return this.http.post(`${this.baseUrl}/profile/upload`, formData, options);
}

【问题讨论】:

  • 您能告诉您 API 代码以及您是如何使用 api 的吗?
  • @Mustahsan 当然!刚刚添加了它们
  • 您是否尝试过不带标头的 http 调用?
  • @Mustahsan 是的,我做到了。结果相同:[org.springframework.web.multipart.MultipartException:当前请求不是多部分请求]

标签: angular spring-boot


【解决方案1】:

您的代码对我来说看起来不错。你不需要在 Angular 中添加标题,也不需要发送options,但我认为这没有什么区别。

我想知道 Angular 是否真的发送了一个文件。您可以通过console.log(file) 进行检查,您可以将其添加到您的前端服务中。

您还可以查看 Spring Boot 中的内容。不如把签名改成

public ResponseEntity&lt;String&gt; uploadData(HttpServletRequest request) throws Exception

这使您可以通过 X 射线来请求,并查看发生了什么。我希望这些指针有用。

【讨论】:

  • 谢谢!事实上,我必须添加 Authorization 标头并且它可以工作
猜你喜欢
  • 1970-01-01
  • 2020-01-28
  • 2019-11-03
  • 2020-10-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-19
  • 1970-01-01
相关资源
最近更新 更多