【发布时间】:2021-11-22 13:37:58
【问题描述】:
您好,我想知道如何发送一个包含 json 对象作为请求主体以及多部分表单数据(Mp4 文件)的单个 axios 发布请求。
在我的示例中,我想发送“详细信息”和“文件”。我尝试将详细信息和文件作为第二个和第三个参数发送给 axios.post() 方法,但据我所知 axios.post 只接受 2 个参数。
我也尝试将详细信息和文件附加到表单数据中,但这也不起作用。
如果我将它们分成 2 个单独的 post call,它可以正常工作,但我的应用程序需要这些一起发生。
我的 spring 控制台中出现以下错误: [org.springframework.web.HttpMediaTypeNotSupportedException:不支持内容类型'multipart/form-data;boundary=----WebKitFormBoundaryqKyZ0R2SyFeDNCVp;charset=UTF-8']
这是我的 Web 开发工具控制台中的错误: xhr.js:210 POST http://localhost:9191/api/123/file/upload 415
非常感谢任何建议
const FileUpload = () => {
const [file, setFile]= useState(null)
const[details, setDetails] = useState({consent:false,
idConfirmed:false,
label:"",
roundId:""})
const changeHandler=(e)=>{
setFile(e.target.files[0]);
setDetails(prevDetails=>({
...prevDetails,
consent:true,
idConfirmed:true,
label:"test_Label"
}));
};
const handleSubmission=(e)=>{
e.preventDefault();
const data = new FormData();
data.append("file", file)
data.append("file", details)
console.log("Data: ", data)
axios.post(`${process.env.REACT_APP_URL_NEW_ROUND_VID}/123/file/upload`, data,
{
headers:{
"Content-Type":"multipart/form-data"
}
})
.then(res=>{
console.log("Data: ",res.data)
console.log("success")
})
.catch((e)=>{
console.log("Error", e)
})
//})
};
这是我在 Springboot 中的休息端点:
@PostMapping(
path = "{patientId}/file/upload",
consumes = MediaType.MULTIPART_FORM_DATA_VALUE,
produces = MediaType.APPLICATION_JSON_VALUE)
public void addWardRound(@PathVariable("patientId") String patientId,
@RequestParam("file") MultipartFile file,
@RequestBody WardRequest wardRequest){
WardRoundService.isFileEmpty(file);
WardRound round = service.saveRound(wardRequest);
String roundId = round.getRoundId();
service.uploadVid(patientId, roundId, file);
}
【问题讨论】:
-
您不能同时将json格式的数据和文件作为二进制数据一起发送。因此您可以使用 formData 结构将 json 数据作为字符串发送,或者使用 Promise.all 方法在 2 个单独的发布请求中发送它们