我正在尝试创建一种将文件从 Reactjs Dropzone 插件附加到 axios POST 请求的方法。
目前,我的模块正在执行以下 ajax 请求:
submitPost() {
const formData = new FormData;
const err = this.validate();
if( !err ) {
this.setState({buttonText: 'Posting...'});
axios.post('/user/post/create/', {
content: this.state.post_content,
images: this.state.images,
headers: {
'Content-Type': 'multipart/form-data'
},
})
.then(response => {
console.log(response);
this.setState({buttonText: 'Success'});
setTimeout(
function() {
this.setState({
buttonText: 'Post',
post_content: '',
images: []
});
$('#post_content').val('');
}.bind(this), 1000
);
}).catch(error => {
console.log(error.response);
this.setState({buttonText: 'Error'});
setTimeout(
function() {
this.setState({buttonText: 'Post'});
}.bind(this), 1000
);
});
} else {
this.setState({buttonText: 'Error'});
setTimeout(
function() {
this.setState({buttonText: 'Post'});
}.bind(this), 1000
);
}
}
并定义了以下状态:
constructor(props){
super(props);
this.state= {
progressValue: '0',
progressText: '0%',
buttonText: 'Post',
post_content: '',
images: []
}
}
这是我使用 Reactjs Dropzone 编写的上传模块:
import React, { Component } from 'react';
import Dropzone from 'react-dropzone'
import $ from "jquery";
export class Uploader extends Component {
constructor(props){
super(props);
this.state= {
images: this.props.images
}
}
onDrop(files) {
this.setState({
images: files
});
console.log(files);
this.props.handleImageUpload(files);
}
render() {
return (
<div className="uploader">
<div className="previews">
{this.state.images.map((file) =>
<div
className="preview"
key={file.preview}>
<img src={file.preview} />
</div>
)}
</div>
<Dropzone onDrop={this.onDrop.bind(this)}>
<p>Try dropping some files here, or click to select files to upload.</p>
</Dropzone>
</div>
);
}
}
任何帮助将不胜感激,我目前正在尝试从图像状态上传文件,该文件以数组的形式出现,但以这种格式出现:
[{"preview":"blob:http://outist.local/3c3fc96b-b89d-41c8-8835-3309be8ac430"},{"preview":"blob:http://outist.local/6cf9aa40-0538-4cef -affe-58951afef2eb"},{"preview":"blob:http://outist.local/4631977b-1301-498d-b4e8-611f9a57b6bb"},{"preview":"blob:http://outist.local /1650a49c-2eed-408c-a035-473cade2bfa6"}]