代码之家  ›  专栏  ›  技术社区  ›  A0__oN

通过单个请求发送JSON和图像。角形+弹簧防尘套

  •  5
  • A0__oN  · 技术社区  · 7 年前

    弹簧座控制器

    @PostMapping(
        value = "/post",
        produces = MediaType.APPLICATION_JSON_VALUE,
        consumes = {MediaType.APPLICATION_JSON_VALUE, MediaType.MULTIPART_FORM_DATA_VALUE}
    )
    public ResponseEntity<User> handleFileUpload(@RequestParam("user") User user, @RequestPart("file") MultipartFile file) {
        // do something with User and file
        return ResponseEntity.ok().build();
    }
    

    角度服务

    @Injectable()
    export class UploadFileService {
    
      constructor(private http: HttpClient) { }
      pushFileToStorage(file: File): Observable<HttpEvent<{}>> {
        let formdata: FormData = new FormData();
        formdata.append('file', file);
        formdata.append('user', JSON.stringify(new User('John', 12)))
    
        const req = new HttpRequest('POST', '/post', formdata, {
          reportProgress: true,
        });
    
        return this.http.request(req);
      }
    }
    

    当我尝试发送请求时,我收到 500 Internal Server Error.

    这是一个请求头

    POST /post HTTP/1.1
    Host: localhost:4200
    Connection: keep-alive
    Content-Length: 152881
    Accept: application/json, text/plain, */*
    Content-Type: multipart/form-data; boundary=----WebKitFormBoundarydaQb5yaWw2xu1V9r
    Accept-Encoding: gzip, deflate, br
    Accept-Language: en-US,en;q=0.9
    

    请求有效负载

    ------WebKitFormBoundarydaQb5yaWw2xu1V9r
    Content-Disposition: form-data; name="file"; filename="Screen Shot 2017-10-24 at 8.49.13 PM.png"
    Content-Type: image/png
    
    
    ------WebKitFormBoundarydaQb5yaWw2xu1V9r
    Content-Disposition: form-data; name="user"
    
    {"name":"John","age":12}
    ------WebKitFormBoundarydaQb5yaWw2xu1V9r--
    

    注意:如果在Spring rest控制器中,我将参数类型User更改为字符串,它就会工作。

    问题:如何从Angular发送请求,以便在Spring上获取用户和多部分文件,而不是字符串。

    1 回复  |  直到 6 年前
        1
  •  7
  •   Saheb jtoberon    7 年前

    改变

    public ResponseEntity<User> handleFileUpload(@RequestParam("user") User user, @RequestPart("file") MultipartFile file)
    

    public ResponseEntity<User> handleFileUpload(@RequestPart("user") User user, @RequestPart("file") MultipartFile file)
    

    将请求更改为类似以下内容将起作用:

    curl -i -X POST -H "Content-Type: multipart/form-data" \
    -F 'user={"name":"John","age":12};type=application/json' \
    -F "file=@myfile.txt" http://localhost:8080/post
    

    对于 consumes 只有 MediaType.MULTIPART_FORM_DATA_VALUE 是必需的。

    要从角度提出上述请求,可以这样做:

    const userBlob = new Blob(JSON.stringify(new User('John', 12)),{ type: "application/json"});
    formdata.append('user', userBlob);