我正在尝试通过我构建的角度 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 中通过。
答案 0 :(得分:0)
我发现了错误,
fd.append('image',this.imageFile)
应该
fd.append('imageFile',this.imageFile)
与后端服务中指定的命名法匹配。