通过单个请求发送JSON和图像.Angular +弹簧靴 [英] Send JSON and Image with single request. Angular + Spring Boot

查看:65
本文介绍了通过单个请求发送JSON和图像.Angular +弹簧靴的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Spring Rest Controller

@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.

When I try to send the request I get 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(用户)更改为String(字符串),则它起作用.

Note: If in Spring rest controller I change parameter type User to String it works.

问题:如何从Angular发送请求,以便在Spring上我可以获取User和MultipartFile而不是String.

Question: How to send request from Angular so that on Spring I can get User and MultipartFile, instead of String.

推荐答案

更改

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

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

并将请求更改为类似的方式将起作用:

and changing the request to something like this will work:

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

仅用于消费 MediaType.MULTIPART_FORM_DATA_VALUE .

要按角度提出上述要求,可以执行以下操作:

To make above kind of request in angular, something like this can be done:

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

这篇关于通过单个请求发送JSON和图像.Angular +弹簧靴的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆