使用单个请求发送 JSON 和图像。角 + 弹簧靴

Ama*_*har 5 spring typescript spring-boot angular

弹簧座控制器

@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();
}
Run Code Online (Sandbox Code Playgroud)

角度服务

@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);
  }
}
Run Code Online (Sandbox Code Playgroud)

当我尝试发送请求时,我得到 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
Run Code Online (Sandbox Code Playgroud)

请求有效载荷

------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--
Run Code Online (Sandbox Code Playgroud)

注意:如果在 Spring rest 控制器中我将参数类型 User 更改为 String 它可以工作。

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

Sah*_*heb 7

改变

public ResponseEntity<User> handleFileUpload(@RequestParam("user") User user, @RequestPart("file") MultipartFile file)
Run Code Online (Sandbox Code Playgroud)

public ResponseEntity<User> handleFileUpload(@RequestPart("user") User user, @RequestPart("file") MultipartFile file)
Run Code Online (Sandbox Code Playgroud)

并将请求更改为这样的内容将起作用:

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
Run Code Online (Sandbox Code Playgroud)

For consumesonlyMediaType.MULTIPART_FORM_DATA_VALUE是必需的。

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

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

  • 我尝试了你的建议,你需要将 `[]` 添加到 `JSON.stringify(new User('John', 12)`: `const myObjStr = JSON.stringify(new User('John', 12); const userBlob = new Blob([myObjStr],{ 类型: "application/json"});` (3认同)