所需的请求部分 'file' 不存在 - Java Spring 和 Angular 7



我在Angular 6中的POST方法有问题。我想向服务器发送图像,我尝试了邮递员,我的弹簧启动工作很好,并且我的图像保存得很好在服务器上,但是当我从Angular项目发送时,我有错误:

2019-02-18 10:40:07.086 WARN 6496 --- [NIO-8080-EXEC-5] .W.S.M.S.DefaulthandLerexceptionResolver:解决 [org.springframework.web.multipart.support.missingservletrequestpartexception: 所需的请求部分"文件"不存在]

这是我的模板:

<input type="file" (change)="onFileSelectedMethod($event)">
<button (click)="onUploadButton()">Upload!</button>

这是我的组成部分:

export class AppComponent implements OnInit {
 selectedFinenew: File = null;
 constructor(private data: DataServiceService, private http: HttpClient) { }
  ngOnInit() {}
 onFileSelectedMethod(event) {
    this.selectedFile = <File>event.target.files[0];
  }
  onUploadButton() {
    const fb = new FormData();
    fb.append('image', this.selectedFile, this.selectedFile.name);
    this.http.post('api/cateogry/dar/uploadFile', fb).subscribe(res => {
      console.log(res);
    }
    );
  }

我在春季引导中的方法:

@PostMapping("/uploadFile")
        public UploadFileResponse uploadFile(@RequestParam("file") MultipartFile file) {
            String fileName = fileStorageService.storeFile(file);
            String fileDownloadUri = ServletUriComponentsBuilder.fromCurrentContextPath()
                    .path("/downloadFile/")
                    .path(fileName)
                    .toUriString();
            return new UploadFileResponse(fileName, fileDownloadUri,
                    file.getContentType(), file.getSize());
        }

您需要在formData中提供file

您应该更改

fb.append('image', this.selectedFile, this.selectedFile.name);

to

fb.append('file', this.selectedFile, this.selectedFile.name);

更改

@RequestParam("file") MultipartFile file

to

@RequestParam("image") MultipartFile file

最新更新