我有这个处理程序来对端点进行 api 调用:
handleFileChange(e) {
e.preventDefault();
fetch(apiAddress)
.then((res) => {
return res.json()
}).then( (res) => {
this.props.onFileChange(JSON.stringify(res));
});
}
我想发送一个文件作为请求的一部分,如下所示:
render(){
getScene();
return (
<form>
<input type='file' name='uploaded_file' />
<button onClick={this.handleFileChange}>Upload</button>
</form>
)
}
如何通过以该表单添加的文件来做到这一点?
最佳答案
这就像将文件发布到 API 一样简单:
handleFileChange(e) {
e.preventDefault();
let fileInput = document.getElementsByName("uploaded_file")[0];
fetch('/yourEndpoint', {
method: 'POST'
body: fileInput.files[0] // This is your file object
headers: {
"Content-Type": fileInput.files[0].type // this is the MIME type of the data *
},
}).then(
response => response.json()
).then( res => {
this.props.onFileChange(JSON.stringify(res))
});
}
* 但请注意,这是从文件扩展名生成的,因此很容易被欺骗
关于javascript - 以文件作为参数的 React Api 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49795426/