使用React在Spring中上传图片

huangapple go评论57阅读模式
英文:

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 &#39;multipart/form-data;boundary=----WebKitFormBoundaryMzjfDQXfdupeZNW2;charset=UTF-8&#39; is not supported

in Browser console:

AxiosError&#160;{message: &#39;Request failed with status code 415&#39;, name: &#39;AxiosError&#39;, code: &#39;ERR_BAD_REQUEST&#39;, config: {…}, request: XMLHttpRequest,&#160;…}

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&lt;Object&gt; 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) =&gt; {
        event.preventDefault()

        const formData = new FormData();
        formData.append(&#39;assettype&#39;, assettype)
        formData.append(&#39;assetBrand&#39;, assetBrand)
        formData.append(&#39;assetModel&#39;, assetModel)
        formData.append(&#39;file1&#39;, image1)
        formData.append(&#39;file2&#39;, image2)
        formData.append(&#39;file3&#39;, image3)

        const asset = {
            assettype,
            assetBrand,
            assetModel,
        }

         const file1 = {
        image1
    }
    const file2 = {
        image2
    }
    const file3 = {
        image3
    }
    axios({
        method: &quot;post&quot;,
        url: &quot;http://localhost:8082/api/assets&quot;,
        data: {
            asset,
            file1,
            file2,
            file3
        },
        headers: {
            &#39;Content-Type&#39;: &#39;multipart/form-data&#39;
        }
    }).then(res =&gt; {
        console.log(res.data)
        console.log(res.headers)
        console.log(res.request)
        console.log(res.status)
    })
    }

If I remove the line with headers:

headers: {
                &#39;Content-Type&#39;: &#39;multipart/form-data&#39;
            }

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=&quot;multipart/form-data&quot; 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&lt;Object&gt; saveAsset(@ModelAttribute Assets assets,
                                            @RequestParam MultipartFile file1,
                                            @RequestParam MultipartFile file2,
                                            @RequestParam MultipartFile file3)  throws IOException {

huangapple
  • 本文由 发表于 2023年5月24日 21:38:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/76324175.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定