正在将文件从 angular 6 应用程序发送到 spring boot web api "Required request part 'file' is not present"

Sending files from angular 6 application to spring boot web api "Required request part 'file' is not present"

我正在尝试将文件从 angular 6 前端发送到 spring 引导网络 API。 但它给了我以下错误

Bad Request","message":"Required request part 'file' is not present

这是我的 html 上传文件的代码

<div class="form-group">
    <label for="exampleInputFile">File input</label>
    <input type="file" name="file" (change)="fileChange($event)" class="form-control-file" id="exampleInputFile" aria-describedby="fileHelp">
 </div>
<button (click)="uploadFile()" type="button" class="btn btn-primary">Upload</button>

这是我的 ts 代码

      formData:FormData = new FormData();
      readytoupload:boolean=false;

      fileChange(event) {
        let fileList: FileList = event.target.files;
        if(fileList.length > 0) {    
            let file: File = fileList[0];    
            this.formData.append('file', file);
            this.readytoupload =true;
        }
      }
      uploadFile(){
           if(this.readytoupload){
            this.featureservice.uploadFIle(this.formData).subscribe(data => {
              const a = data.json();
              this.goToProcess(a.process_id)
            });
           }
      }

这里是 angular 服务

  uploadFIle(formData:FormData){
    let headers = new Headers();
    headers.append('Accept', 'application/json');
    headers.append("Content-Type", 'multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW');
    return this.http.post(this.url+'upload',formData,{headers: headers})
  };

这是后端控制器

@CrossOrigin(origins = "*")
@PostMapping(value = "api/upload")
public String uploadReviews(@RequestParam("file") MultipartFile file, RedirectAttributes redirectAttributes) {    
    if (file.isEmpty()) {    
        return null;
    }    
    try {

        byte[] bytes = file.getBytes();
        Path path = Paths.get(uploadFolder + file.getOriginalFilename());
        uploadFile = path.toString();
        Files.write(path, bytes);
        sessionID = "6";   
    } catch (IOException e) {    
        e.printStackTrace();    
       return null;


    return sessionID;
}

above API 服务可以完美地处理 Postman 请求。但不适用于 angular 个请求。

谁能帮我解决这个问题?

而不是这个:-

return this.http.post(this.url+'upload',formData,{headers: headers})

使用这个:-

return this.http.post(this.url+'upload',{"file" : formData},{headers: headers})

希望对您有所帮助

这对我有用

downloadPdf(file: File): Observable<HttpEvent<any>>{

    const formData: FormData = new FormData();
    formData.append('file', file);
    const req = new HttpRequest('POST', `${this.url}/upload`, formData, {
      reportProgress: true,
      responseType: 'arraybuffer' as 'json'
    });
     return this.http.request(req);
}