【问题标题】:Required request part 'file' is not present- Java Spring and Angular 7所需的请求部分“文件”不存在-Java Spring 和 Angular 7
【发布时间】:2019-07-11 16:13:53
【问题描述】:

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

2019-02-18 10:40:07.086 警告 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);
    }
    );
  }

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

【问题讨论】:

  • 你能分享你的Controller Java 代码吗?
  • 是的,现在你可以看到了。
  • 你找到解决办法了吗?

标签: angular spring-boot


【解决方案1】:

您需要在您的formData 中提供file。

你应该改变

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

到

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

或

改变

@RequestParam("file") MultipartFile file

到

@RequestParam("image") MultipartFile file

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-08-23
    • 2017-04-06
    • 2019-09-08
    • 1970-01-01
    • 1970-01-01
    • 2017-10-09
    • 2020-10-22
    相关资源
    最近更新 更多