英文:
Uploading images in spring using react
问题
如何解决Spring中的415状态问题?
我正在尝试使用React将图像上传到数据库,但一直收到以下错误:
在Spring控制台:
Content-Type 'multipart/form-data;boundary=----WebKitFormBoundaryMzjfDQXfdupeZNW2;charset=UTF-8'不受支持
在浏览器控制台:
AxiosError {message: 'Request failed with status code 415', name: 'AxiosError', code: 'ERR_BAD_REQUEST', config: {...}, request: XMLHttpRequest,...}
我尝试在数据库中添加项目和相关图像。其中项目的ID与图像一起添加。在Spring中,我创建了图像和项目的实体。在项目实体中,我创建了一个方法,将接收到的图像作为实体添加到数据库中:
private Image toImageEntity(MultipartFile file) throws IOException {
Image image = new Image();
image.setImageName(file.getName());
image.setOriginalFileName(file.getOriginalFilename());
image.setContentType(file.getContentType());
image.setSize(file.getSize());
image.setBytes(file.getBytes());
return image;
}
在项目实体中,我接收图像和项目主体作为参数:
@PostMapping(consumes = {MediaType.MULTIPART_FORM_DATA_VALUE, MediaType.APPLICATION_JSON_VALUE})
public ResponseEntity<Object> saveAsset(@RequestBody Assets assets,
@RequestParam MultipartFile file1,
@RequestParam MultipartFile file2,
@RequestParam MultipartFile file3) throws IOException {
// 处理图像上传逻辑
Assets itemFromDB = assetsRepository.save(assets);
itemFromDB.setPreviewImageId(itemFromDB.getImages().get(0).getId());
assetsRepository.save(assets);
return ResponseEntity.ok().build();
}
在React中,我创建了将数据发送到Spring的方法:
const saveAsset = (event) => {
event.preventDefault()
const formData = new FormData();
// 添加表单数据和文件
axios({
method: "post",
url: "http://localhost:8082/api/assets",
data: {
asset,
file1,
file2,
file3
},
headers: {
'Content-Type': 'multipart/form-data'
}
}).then(res => {
// 处理响应
})
}
如果我从axios中删除headers
行,浏览器控制台将显示500错误,但Spring控制台显示当前不是多部分请求。
我在表单标签中添加了enctype="multipart/form-data"
,但仍然收到错误。
我尝试过使用FormData
进行POST,或使用FileList
进行postForm
,但都收到415错误状态。有什么想法吗?
英文:
how to solevt he issue with status 415 in spring?
I am trying to upload the images in DB with react, but all the time receive the errors:
in Spring console :
Content-Type 'multipart/form-data;boundary=----WebKitFormBoundaryMzjfDQXfdupeZNW2;charset=UTF-8' is not supported
in Browser console:
AxiosError {message: 'Request failed with status code 415', name: 'AxiosError', code: 'ERR_BAD_REQUEST', config: {…}, request: XMLHttpRequest, …}
I am trying to add the Item in DB and Images in related DB. Where ID of items are added with images. In the Spring I created the entities for images and items. In Items entity I created the method which add the images, which are received with item, as entity and put them in DB :
private Image toImageEntity(MultipartFile file) throws IOException {
Image image = new Image();
image.setImageName(file.getName());
image.setOriginalFileName(file.getOriginalFilename());
image.setContentType(file.getContentType());
image.setSize(file.getSize());
image.setBytes(file.getBytes());
return image;
}
In the Item entities I receive the images and Item body as params :
@PostMapping(consumes = {MediaType.MULTIPART_FORM_DATA_VALUE, MediaType.APPLICATION_JSON_VALUE})
public ResponseEntity<Object> saveAsset(@RequestBody Assets assets,
@RequestParam MultipartFile file1,
@RequestParam MultipartFile file2,
@RequestParam MultipartFile file3) throws IOException {
Image image1;
Image image2;
Image image3;
if(file1.getSize() != 0){
image1 = toImageEntity(file1);
image1.setPreviewImage(true);
assets.addImageToItemName(image1);
}
if(file2.getSize() != 0){
image2 = toImageEntity(file2);
assets.addImageToItemName(image2);
}
if(file3.getSize() != 0){
image3 = toImageEntity(file3);
assets.addImageToItemName(image3);
}
System.out.println(assets);
Assets itemFromDB = assetsRepository.save(assets);
itemFromDB.setPreviewImageId(itemFromDB.getImages().get(0).getId());
assetsRepository.save(assets);
return ResponseEntity.ok().build();
}
In react I created the method for send the data to Spring :
const saveAsset = (event) => {
event.preventDefault()
const formData = new FormData();
formData.append('assettype', assettype)
formData.append('assetBrand', assetBrand)
formData.append('assetModel', assetModel)
formData.append('file1', image1)
formData.append('file2', image2)
formData.append('file3', image3)
const asset = {
assettype,
assetBrand,
assetModel,
}
const file1 = {
image1
}
const file2 = {
image2
}
const file3 = {
image3
}
axios({
method: "post",
url: "http://localhost:8082/api/assets",
data: {
asset,
file1,
file2,
file3
},
headers: {
'Content-Type': 'multipart/form-data'
}
}).then(res => {
console.log(res.data)
console.log(res.headers)
console.log(res.request)
console.log(res.status)
})
}
If I remove the line with headers
:
headers: {
'Content-Type': 'multipart/form-data'
}
from axios, the console of browser show me error 500, but Spring console shows - that current is not multipart request.
in form tag I put enctype="multipart/form-data"
but any way I receive the errors.
I tried post with FormData
, or postForm
with a FileList
but I receive the error status 415
any ideas?
答案1
得分: 1
I think the problem is in your controller:
@RequestBody
意味着将 JSON 数据解析为映射或 Java Beans,仅支持内容类型为 "application/json;charset=UTF-8";
也许你可以尝试使用 @ModelAttribute
:
@PostMapping(consumes = {MediaType.MULTIPART_FORM_DATA_VALUE, MediaType.APPLICATION_JSON_VALUE})
public ResponseEntity<Object> saveAsset(@ModelAttribute Assets assets,
@RequestParam MultipartFile file1,
@RequestParam MultipartFile file2,
@RequestParam MultipartFile file3) throws IOException {
英文:
I think the problem is in your controller:
@RequestBody
means to parse JSON data into map or java beans and only support content type is "application/json;charset=UTF-8"
Maybe you can try with @ModelAttribute
:
@PostMapping(consumes = {MediaType.MULTIPART_FORM_DATA_VALUE, MediaType.APPLICATION_JSON_VALUE})
public ResponseEntity<Object> saveAsset(@ModelAttribute Assets assets,
@RequestParam MultipartFile file1,
@RequestParam MultipartFile file2,
@RequestParam MultipartFile file3) throws IOException {
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论