【发布时间】:2019-04-25 13:40:29
【问题描述】:
我尝试通过 post 方法从 ionic 前端应用程序将 图像 发送到 中的后端服务弹簧靴
我已经完成了这种方法,该方法使用 FormData 对象内的图像将帖子发送到后端 url:
uploadImageService(url: string, image: any) {
console.log('post service: upload Image', + url);
// Initiates a FormData object to be sent to the server
const fd: FormData = new FormData();
fd.append('file', image);
const xhr = new XMLHttpRequest;
console.log('form data file: \n' + fd.get('file'));
xhr.open('POST', url);
// Send the FormData
xhr.send(fd);
console.log(xhr.response);
return xhr.responseText;
}
// call this method:
this.webapiService.uploadImageService(this.globalDataService.getUrlMedium() 'riskcontrol/subir-imagen', this.selectedImage);
这是收集本帖的spring boot方法:
@RequestMapping(method = RequestMethod.POST, value = "/subir-imagen")
public ResponseEntity handleFileUpload(@RequestParam("file") MultipartFile file) {
LOGGER.log(Level.INFO, "/Post, handleFileUpload", file);
String associatedFileURL = fileManagerService.storageFile(file);
return ResponseEntity.ok(associatedFileURL);
}
当我发布图片时,我收到此错误:
.w.s.m.s.DefaultHandlerExceptionResolver:已解决 [org.springframework.web.multipart.support.MissingServletRequestPartException:所需的请求部分“文件”不存在]
我已经通过 Postman 发起了请愿,并且成功了, 这就是为什么我认为错误出在 tyscript 代码中。
我在邮递员和代码之间看到的唯一区别是,在表单数据中,让我们将 key 标记为 type file 或 type text,我选择了文件类型。
我尝试以另一种方式发布请求:
const httpOptionsImages = {
headers: new HttpHeaders({
'Content-Type': 'multipart/form-data',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET, PUT, POST, DELETE'
})
};
// function
uploadImageService(url: string, image: any): Observable<any> {
console.log('post service: upload Image', + url);
// Initiates a FormData object to be sent to the server
const fd: FormData = new FormData();
fd.append('file', image);
return this.http
.post(url, fd, httpOptionsImages);
}
// call to the function
this.webapiService.uploadImageService(this.globalDataService.getUrlMedium() + 'riskcontrol/subir-imagen', this.selectedImage)
.subscribe( result => {
console.log(result);
});
但是这样我又得到了一个错误:
FileUploadException: 请求被拒绝,因为没有找到多部分边界
我做错了什么? 有什么方法可以向 FormData 表明密钥的类型是 file,就像邮递员一样?
【问题讨论】:
标签: spring post multipartform-data ionic4 multipart