首页 > 解决方案 > 所需的请求部分“文件”不存在-Java Spring 和 Angular 7

问题描述

我在 Angular 6 中的方法有问题POST。我想将图像发送到服务器,我从 Postman 尝试过,我的 Spring boot 工作得很好,我的图像保存在服务器上,但是当我从 Angular 项目发送时我有错误:

2019-02-18 10:40:07.086 WARN 6496 --- [nio-8080-exec-5] .wsmsDefaultHandlerExceptionResolver:已解决 [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);
    }
    );
  }

我在 Spring Boot 中的方法:

@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());
        }

标签: angularspring-boot

解决方案


您需要file在您的formData.

你应该改变

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

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

或者

改变

@RequestParam("file") MultipartFile file

@RequestParam("image") MultipartFile file


推荐阅读