可以将一个文件以formData格式传输吗?

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

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) =&gt; {
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: { &quot;Content-Type&quot;: &quot;multipart/form-data&quot; } }
);

The return function of the component is as follows to render the form

&lt;form onSubmit={handleSubmit(onSubmit)} encType=&quot;multipart/form-data&quot;&gt;
Id: &lt;br /&gt;
&lt;input type=&quot;text&quot; {...register(&quot;id&quot;)} defaultValue={id} readOnly /&gt;
&lt;br /&gt;
Name: &lt;br /&gt;
&lt;input type=&quot;text&quot; {...register(&quot;name&quot;)} required /&gt;
 
Image: &lt;br /&gt;
&lt;input type=&quot;file&quot; {...register(&quot;image&quot;)} required/&gt;
&lt;br /&gt;
&lt;input type=&quot;submit&quot; value=&quot;Submit&quot; required/&gt;
&lt;/form&gt;

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.

huangapple
  • 本文由 发表于 2023年6月15日 12:23:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/76479094.html
匿名

发表评论

匿名网友

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

确定