【发布时间】:2020-09-10 05:07:49
【问题描述】:
我正在尝试在 django 后端使用 react js 上传图像但是当我尝试上传图片并检查它时console.log() 图像文件存在那里并且一旦我提交表单图像文件对象 shsows {} 空我不为什么我提交的节目一直在上传,但图像一直显示为空,这是我到目前为止所做的代码。这里也是代码沙箱链接的链接。 https://codesandbox.io/s/thirsty-varahamihira-fnusu?file=/src/App.js:0-1494。谢谢。
import React, { Component } from "react";
import "./styles.css";
class App extends Component {
constructor(props) {
super(props);
this.state = {
image: null
};
}
handleInputChange = async (event) => {
await this.setState({
[event.target.name]: event.target.files[0]
// image: event.target.files[0]
});
};
handleSubmit = (e) => {
e.preventDefault();
const formdata = new FormData();
formdata("image", this.state.image);
fetch(`https://inback.herokuapp.com/api/1/blog/image/list/`, {
method: "POST",
headers: {
"Content-Type": "multipart/form-data",
Authorization: "Bearer 6tEg0RinS5rxyZ8TX84Vc6qXuR2Xxw"
},
body: formdata
})
.then((response) => {
if (response.ok) {
alert("Success");
} else {
alert("error");
}
})
.catch((err) => {
console.log(err);
});
};
render() {
return (
<div id="other" className="">
<p className="mod" style={{ marginTop: "10px" }}>
Uplaod
</p>
<hr></hr>
<form onSubmit={this.handleSubmit}>
<input type="file" name="image" onChange={this.handleInputChange} />
<button>Submit</button>
</form>
</div>
);
}
}
export default App;
【问题讨论】:
标签: javascript django reactjs