【问题标题】:Uploading image to spring rest service using Angular使用Angular将图像上传到spring rest服务
【发布时间】:2020-07-12 19:41:59
【问题描述】:

我正在尝试使用 x-wwww-form-urlencoded 内容类型向我的 Spring Boot 服务发送一个 http 请求,但我不确定我做错了什么。

这是我的角度代码:

img(desc:HTMLInputElement, selectedFile){
    let url = "http://localhost:8080/api/v1/upload_image"

    const body = new HttpParams()
    body.set("image", selectedFile)
    body.set("description", desc.value)

    return this.http.post<Isecurity[]>(url, body.toString(),{
      headers:new HttpHeaders()
      .set('Content-Type', 'application/x-www-form-urlencoded')
    } )
  }

这是我的 Spring 服务:

@PostMapping("upload_image")
@CrossOrigin
public  Map<String, Boolean> upload_image(@RequestParam MultipartFile image, @RequestParam String description) {
        Map<String, Boolean> values = new HashMap<>();
        values.put("response", true);
        return values;
}

我收到 500 服务器错误。任何帮助将不胜感激。

【问题讨论】:

  • 使用 FormData 发送

标签: angular spring


【解决方案1】:

我认为您以错误的方式传递参数。您只是将 params 的名称保留为 body,但它实际上不是 body。

您需要使用 '?' 传递参数在网址之后。

因此,您必须将 .ts 文件中的代码更新为以下几行:

img(desc:HTMLInputElement, selectedFile){
    let url = "http://localhost:8080/api/v1/upload_image?"

    const body = new HttpParams()
    body.set("image", selectedFile)
    body.set("description", desc.value)

    return this.http.post<Isecurity[]>(url+body.toString(),{
      headers:new HttpHeaders()
      .set('Content-Type', 'application/x-www-form-urlencoded')
    } )
  }

这都是关于传递参数的,但我认为你应该将图像作为 body 而不是作为其余 api 中的参数。

【讨论】:

  • 如果该解决方案对您有用,也请点赞,这样也可以对其他人有所帮助。
猜你喜欢
  • 2012-07-15
  • 2019-11-22
  • 2013-04-28
  • 2018-03-12
  • 2019-09-23
  • 2013-04-07
  • 2021-10-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多