我正在尝试创建一个页面,用户可以在其中发布图像及其详细信息 . 现在我正在测试邮递员的 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 回答
您需要将 Headers 内容类型设置为multipart / form-data . 修改您的服务方法,如下所示,并尝试 .
请注意,此外,您还需要在 Headers 中设置响应类型(即接受) . 如果有效,请告诉我们 .