Angular 4-如何将文件上传到后端?

时间:2018-12-05 13:52:23

标签: angular spring-boot

我正在尝试从Angle 4前端上载多个文件到Spring Boot服务器。

 selectedFile : File []  = [];
  filesToUpload: File[] = [];
  selectedFileNames: string[] = [];

  readURL(fileInput) {
    // this.detectFiles(fileInput);
    this.filesToUpload = <Array<File>>fileInput.target.files;
    for (let i = 0; i < this.filesToUpload.length; i++)
    {
        this.selectedFile.push(fileInput.target.files[i]);
    }
    console.log(this.selectedFile)
}

onUpload2(){
    const fd = new FormData();
    for (var i = 0; i < this.filesToUpload.length; i++){
      fd.append('fileseee',this.selectedFile[i],this.selectedFile[i].name);
    }

    this.questionService.uploadImages(fd).
    subscribe( 
      (data: any) => {
           }
         )
   }



uploadImages(fda){
  console.log(fda);
  return this.http.post(this.apiUrl+"/imageUpload112",fda)
  .map((res : Response) => res);
}

后端Spring引导代码与邮递员一起正常工作。显示的错误是

Request processing failed; nested exception is
[org.springframework.web.multipart.MultipartException: Current request is not a multipart request] with root cause

我的邮递员详细信息:

enter image description here

弹簧控制器代码:

@SuppressWarnings("deprecation")
@RequestMapping(method = RequestMethod.POST, value = "/imageUpload112")
public String uploadFile(@RequestParam("fileseee")MultipartFile[] fileStream)
        throws IOException, ServletException {

    String bucketName = "mcqimages";
    String status = "";
    String url = "";

    for (int i = 0; i < fileStream.length; i++) {
        MultipartFile file = fileStream[i];

        try {
            checkFileExtension(file.getName());
            DateTimeFormatter dtf = DateTimeFormat.forPattern("-YYYY-MM-dd-HHmmssSSS");
            DateTime dt = DateTime.now(DateTimeZone.UTC);
            String dtString = dt.toString(dtf);
            String fileName = file.getOriginalFilename();

            BlobInfo blobInfo =
                    storage.create(
                            BlobInfo
                                    .newBuilder(bucketName, fileName)
                                    .setAcl(new ArrayList<>(Arrays.asList(Acl.of(User.ofAllUsers(), Role.READER))))
                                    .build(),
                            file.getInputStream()
                    );

            System.out.println(blobInfo.getMediaLink());
         // status = status + "You successfully uploaded file=" + file.getOriginalFilename();
            url= url+ blobInfo.getMediaLink() + ",";

        } catch (Exception e) {
            status = status + "Failed to upload " + file.getOriginalFilename() + " " + e.getMessage();
        }
    }
    return url;
}

2 个答案:

答案 0 :(得分:1)

您需要确保Spring控制器和Angular网页都使用相同的标题“ multipart / form-data”

Angular上传方法示例:

return this.http.post(`/file`, formData, {
  headers: {
    'enctype': 'multipart/form-data; boundary=request-boundary',
    'Accept': 'application/json'
  }
});

Spring Controller的示例:

@PostMapping(path = "/file", consumes = "multipart/form-data")
public ImageResponse uploadImageFile(@RequestParam("imageFile") MultipartFile[] imagefiles) {
    return imageService.saveImageFiles(imagefiles);
}

答案 1 :(得分:0)

当您将文件推送到存储中时,您不是发送标题吗?

我这样做是

pushFileToStorage(file: File) {
    const body: FormData = new FormData();
    body.append('file', file);
    const headers = new Headers({
      'X-Requested-With': 'XMLHttpRequest'
    });

    return this.http.post(this.urlEndpoint, body, { headers })
      .map(respuesta => {
        console.log(respuesta.json());
        return respuesta.json();
      });
  }