reactjs 415将对象和文件同时发送到服务器时出错

bwntbbo3  于 2023-02-08  发布在  React
关注(0)|答案(1)|浏览(199)

我想把文件和对象同时发送到服务器,但是我得到415错误。我使用react-hook-form库

    • 前端**
const headers = {
        'Content-Type': 'multipart/form-data',
        Authorization: `Bearer ${token}`,
    }

    const handleFormSubmit = async (e) => {

        const data = [{
            petname: e.petname,
            age: e.age,
            type: e.type,
            weight: e.weight,
            firstmet: e.firstmet
        }];

        const formData = new FormData();

        formData.append("file", e.file[0]);
        formData.append("request", new Blob([JSON.stringify(data)], {contentType:"application/json"}))

        console.log(formData)

        await axios.post("http://localhost:5000/api/pet/petform", formData, {
            headers: headers
        })
            .then((response) => {})
            .catch((error) => {})
    }
    • 后端**
@PostMapping(value = "/petform",
            consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public void save(@RequestPart(value="file", required = false) MultipartFile file,
                     @RequestPart(value="request", required = false) PetDTO petDTO) throws IOException {

    }
    • 错误代码**
Request failed with status code 415

当参数发送给 Postman 时,Spring Boot被正常盖章。
enter image description here
enter image description here

2uluyalo

2uluyalo1#

这里有一个数组:

const data = [{
            petname: e.petname,
            age: e.age,
            type: e.type,
            weight: e.weight,
            firstmet: e.firstmet
        }];

应该是

const data = {
            petname: e.petname,
            age: e.age,
            type: e.type,
            weight: e.weight,
            firstmet: e.firstmet
        };

要匹配请求

相关问题