首页 文章

Angular SpringBoot Multipart文件上传

提问于
浏览
0

我正在尝试创建一个页面,用户可以在其中发布图像及其详细信息 . 现在我正在测试邮递员的 spring 启动服务,我成功地获得了服务中的文件 . 当我试图从angular5做同样的事情时,多部分文件在服务中没有被识别,并且总是得到空数组 .

@RequestMapping(value= "/upload", method=RequestMethod.POST)
public AppResponse<User> saveUser(@RequestParam("userId") Long userId, @RequestParam("files") List<MultipartFile> files, HttpServletRequest request){
    int i=0;
    User user=userLogic.getUserById(userId);
    String[] imageUrls= new String[files.size()];
    try {
        for(MultipartFile file:files) {
            if(file.getContentType().equals("image/jpeg") || file.getContentType().equalsIgnoreCase("image/pjpeg")) {
                ObjectMetadata meta= new ObjectMetadata();
                meta.setContentType(file.getContentType());
                meta.setContentDisposition(userId+"_"+i);
                PutObjectResult result=s3Client.putObject(PHOTO_DIRECTORY,getFileName(userId, i),file.getInputStream(),meta);
                imageUrls[i]=PHOTO_DIRECTORY+"/"+getFileName(userId, i);
            } else {
                throw new InvalidFileFormatException("This filetype is not accepted");
            }

        }
        user.setActorPhotos(imageUrls);
        userLogic.saveUser(user);
        return new AppResponse<>(false, "Success");
    }
    catch(InvalidFileFormatException | IOException e) {
        System.err.println("Exception in file upload");
        return new AppResponse<>(true, "Failure");
    }

我的角度服务代码如下

postPhotos(files: any,userId:any): Observable<any> {
 let formData = new FormData();
 formData.append("files",files,"files");   
  return this.http.post<Result>(URLConfig.postPhotos+"?userId="+userId, formData);

}

我尝试从angular添加类似multipart / form-data的 Headers ,并将其设置为undefined . 无论哪种方式,我都会收到错误 . 我在发布之前已经广泛搜索了stackoverflow,并在没有任何帮助的情况下尝试了所有这些解决方案

在此先感谢您的帮助 .

1 回答

  • 0

    您需要将 Headers 内容类型设置为multipart / form-data . 修改您的服务方法,如下所示,并尝试 .

    postPhotos(files: any,userId:any): Observable<any> { 
      const url = "whatever /the/ url is ";
      let headers = new HttpHeaders({
              'Content-Type':'multipart/form-data'
                 });
            let options = { headers: headers };
         return this.http.post<Result>(url, formData,options);  
     }
    

    请注意,此外,您还需要在 Headers 中设置响应类型(即接受) . 如果有效,请告诉我们 .

相关问题