英文:
Can I transfer a file in an object in formData format?
问题
以下是要翻译的部分:
我正在使用React,并希望以multipart/formData格式发送数据。但我从未以这种格式传输文件,所以请给我一些建议!
英文:
The forms provided by BackEnd are as follows
{
dataInputDto: {
itemIndex: string,
addAuditData: {
dataAnswer: string,
fileList: Array<File>
}
}
}
I am using React and would like to send the data in multipart/formData format. But I've never transferred a file in that format, so please give me some advice!
答案1
得分: 0
希望你一切都好。
让我分享给你一段代码片段,以便你可以参考并继续操作。
用于 formData 的提交函数
const onSubmit = async (data) => {
let formdata = new FormData();
formdata = { ...formdata, img: data.image[0] };
console.log(formdata, formdata.img.name);
let response = await axios.post(
`${process.env.REACT_APP_BASEURL}/uploadImg`,
formdata,
{ headers: { "Content-Type": "multipart/form-data" } }
);
}
组件的返回函数如下,用于渲染表单
<form onSubmit={handleSubmit(onSubmit)} encType="multipart/form-data">
Id: <br />
<input type="text" {...register("id")} defaultValue={id} readOnly />
<br />
Name: <br />
<input type="text" {...register("name")} required />
Image: <br />
<input type="file" {...register("image")} required/>
<br />
<input type="submit" value="Submit" required/>
</form>
以上代码段是关于图像的,但你也可以用同样的方式进行文件传输。
如果这对你的问题有用,请接受答案。谢谢与问候。
英文:
Hope You're doing well.
Let me share you a code snippet for the same so you may refer it and proceed further.
The Submit function for the formData
const onSubmit = async (data) => {
let formdata = new FormData();
formdata = { ...formdata, img: data.image[0] };
console.log(formdata, formdata.img.name);
let response = await axios.post(
`${process.env.REACT_APP_BASEURL}/uploadImg`,
formdata,
{ headers: { "Content-Type": "multipart/form-data" } }
);
The return function of the component is as follows to render the form
<form onSubmit={handleSubmit(onSubmit)} encType="multipart/form-data">
Id: <br />
<input type="text" {...register("id")} defaultValue={id} readOnly />
<br />
Name: <br />
<input type="text" {...register("name")} required />
Image: <br />
<input type="file" {...register("image")} required/>
<br />
<input type="submit" value="Submit" required/>
</form>
The Above Code Snippet is refering to image but you may also proceed same for transfering the file.
Kindly Accept the Answer if it works for your query. Thanks & Regards.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论