javascript - 反应 dropzone 不能用 axios 发布
问题描述
我正在尝试在我的代码中使用 react-dropzone 并使用 axios 向服务器发出 POST 请求,但是 POST 请求总是失败并且我不断收到以下错误:
未捕获(承诺中)错误:请求失败,状态码为 500
这是我的组件
constructor(props) {
super(props);
this.state = {
accepted: [],
};
['handleChange', 'handleValidSubmit'].forEach(v => {
this[v] = this[v].bind(this);
});
}
handleValidSubmit(event, values) {
const data = {
accepted: this.state.accepted,
};
console.log(data);
axios({
method: 'post',
url:
'https://oc6tq8iop5.execute-api.ap-southeast-1.amazonaws.com/dev/upload',
data: JSON.stringify(data),
}).then(data => {
console.log(data);
onDrop: accepted => {
accepted.forEach(file => {
req.attach(file.name, file);
});
req.end(callback);
var formData = new FormData();
formData.append('gambar', values.accepted);
console.log(formData);
};
});
}
handleChange(event) {
const { target } = event;
const value = target.type === 'checkbox' ? target.checked : target.value;
const { name } = target;
this.setState({
[name]: value,
});
}
这是我的渲染方法
<div className="dropzone">
<Dropzone
accept="image/jpeg, image/png, image/jpg"
onDrop={accepted => {
this.setState({ accepted });
}}
maxSize={200000}
multiple={false}
>
<p>Maksimal 2 MB (JPG/PNG)</p>
</Dropzone>
{this.state.accepted.map(f => (
<span key={f.name}>
{f.name} - {f.size} bytes
</span>
))}
</div>
解决方案
您只需要使用 axios 发送标头,
const config = { headers: { 'Content-Type': 'multipart/form-data' } };
let fd = new FormData();
values.map((file) => {
fd.append('File[]',file);
});
axios.post(`${ROOT_URL}/ImageUpload`, fd, config)
.then((response) => {
callback(response);
})
.catch(error => {
errorResponse(error);
})
推荐阅读
- python - 更改像素以提高图片的对比度
- python - 我可以为 Python 中的某些属性错误设置异常吗?
- c++ - 返回类型的自动扣除
- sql - 是否可以将数据库声明为变量?
- java - Spring Boot - @Convert 不调用 convertToDatabaseColumn 方法
- keras - LSTM时间序列数据分类模型准确率低
- python - botocore.errorfactory.ProvisionedThroughputExceededException from boto3 for DynamoDB while running spark job
- javascript - 如何在 UI 列表中单击按钮时使用颜色获取多个值?
- assembly - 使用两个连续的 mov 指令时访问冲突
- amazon-web-services - 重启和停止 EC2 实例的费用