尝试通过 angular 发送带有图像的 post 请求时出现 400 错误

时间:2021-07-17 20:10:18

标签: angular spring image post http-status-code-400

我正在尝试通过我构建的角度 UI 发送发布请求,但出现以下错误:

    core.js:6456 ERROR 
HttpErrorResponse {headers: HttpHeaders, status: 400, statusText: "OK", url: "http://localhost:8080/upload", ok: false, …}
error: {timestamp: "2021-07-17T19:59:09.036+00:00", status: 400, error: "Bad Request", path: "/upload"}
headers: HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, lazyInit: ƒ}
message: "Http failure response for http://localhost:8080/upload: 400 OK"
name: "HttpErrorResponse"
ok: false
status: 400
statusText: "OK"
url: "http://localhost:8080/upload"
__proto__: HttpResponseBase

下面是我的 component.ts 文件:

  onFileSelected(event: any){
    console.log(event)
    this.imageFile = event.target.files[0]
  }

  //send post request to MySQL
  uploadImage(){
    const fd = new FormData(); 
    fd.append('image',this.imageFile)
    this.httpClient.post("http://localhost:8080/upload",fd)
      .subscribe(res=>{
        console.log(res);
      })
  }

我的 HTML 文件:

<input type="file" class="file-input" (change) = "onFileSelected($event)"
       #fileUpload>

<div class="file-upload">

    <button mat-mini-fab color="primary" class="upload-btn"
      (click)="fileUpload.click()" style="position:relative;top:25px;"  >
        <mat-icon>attach_file</mat-icon> 
    </button>

    <button mat-button style="position:relaive;left:1px;" (click) = "uploadImage()">Upload file</button>
</div>

还有我的后端服务:

   @CrossOrigin(origins = "http://localhost:4200")
    @PostMapping("/upload")
    public ResponseEntity.BodyBuilder uploadImage(@RequestParam("imageFile") MultipartFile file) throws IOException {

        System.out.println("Original Image Byte Size - " + file.getBytes().length);
        model img = new model(file.getOriginalFilename(), file.getContentType(),
                compressBytes(file.getBytes()));
        userRepository.save(img);
        return ResponseEntity.status(HttpStatus.OK);
    }

为什么我会收到这个错误?看起来一切对我来说都是正确的,post 请求也在 Postman 中通过。

1 个答案:

答案 0 :(得分:0)

我发现了错误,

fd.append('image',this.imageFile)

应该

fd.append('imageFile',this.imageFile)

与后端服务中指定的命名法匹配。