React - 带有文件和字符串的 Axios POST 表单数据
Posted
技术标签:
【中文标题】React - 带有文件和字符串的 Axios POST 表单数据【英文标题】:React - Axios POST form data with files and strings 【发布时间】:2019-01-17 21:09:20 【问题描述】:我必须创建Axios POST
,其中body
类型是form-data
。有些键是字符串,有些是文件。邮递员要求:
如何添加上传按钮以获取文件进入状态,以及如何发出Axios
请求?
【问题讨论】:
【参考方案1】:import React, Component from 'react';
import axios from "axios";
class FileUpload extends Component
// API Endpoints
custom_file_upload_url = `YOUR_API_ENDPOINT_SHOULD_GOES_HERE`;
constructor(props)
super(props);
this.state =
image_file: null,
image_preview: '',
// Image Preview Handler
handleImagePreview = (e) =>
let image_as_base64 = URL.createObjectURL(e.target.files[0])
let image_as_files = e.target.files[0];
this.setState(
image_preview: image_as_base64,
image_file: image_as_files,
)
// Image/File Submit Handler
handleSubmitFile = () =>
if (this.state.image_file !== null)
let formData = new FormData();
formData.append('customFile', this.state.image_file);
// the image field name should be similar to your api endpoint field name
// in my case here the field name is customFile
axios.post(
this.custom_file_upload_url,
formData,
headers:
"Authorization": "YOUR_API_AUTHORIZATION_KEY_SHOULD_GOES_HERE_IF_HAVE",
"Content-type": "multipart/form-data",
,
)
.then(res =>
console.log(`Success` + res.data);
)
.catch(err =>
console.log(err);
)
// render from here
render()
return (
<div>
/* image preview */
<img src=this.state.image_preview />
/* image input field */
<input
type="file"
onChange=this.handleImagePreview
/>
<label>Upload file</label>
<input type="submit" onClick=this.handleSubmitFile value="Submit"/>
</div>
);
export default FileUpload;
【讨论】:
【参考方案2】:只需在“文件”类型的输入上触发 onChange 事件中的方法,并以“multipart/form-data”格式发送到服务器:
<Input id="file" type="file" onChange=this.uploadFile />
let formData = new FormData();
/*
Iteate over any file sent over appending the files
to the form data.
*/
for( var i = 0; i < this.files.length; i++ )
let file = this.files[i];
formData.append('files[' + i + ']', file);
/*
Make the request to the POST /select-files URL
*/
axios.post( '/select-files',
formData,
headers:
'Content-Type': 'multipart/form-data'
).then(function()
console.log('SUCCESS!!');
)
.catch(function()
console.log('FAILURE!!');
);
【讨论】:
输入不应该在前端可见,只有带有文本Upload
的按钮。我的问题是如何为上述示例创建Axios post
?
这是另一个问题,另一个问题。样式和输入是另一个主题,谷歌足以回答。以上是关于React - 带有文件和字符串的 Axios POST 表单数据的主要内容,如果未能解决你的问题,请参考以下文章