React 文件实现上传功能
程序员文章站
2022-06-17 08:18:22
class Home extends React.Component { constructor(props) { super(props); this.state = { imgUrl: '', file: null }; // 为了在回调中使用 `this`,这个绑定是必不可少的 this.fileChange = this.fileChange.bind(this); this.upload = this.upload.bi...
class Home extends React.Component {
constructor(props) {
super(props);
this.state = {
imgUrl: '',
file: null
};
// 为了在回调中使用 `this`,这个绑定是必不可少的
this.fileChange = this.fileChange.bind(this);
this.upload = this.upload.bind(this);
}
fileChange({target}) {
console.log(target.files);
console.log(target.files[0]);
this.setState({
file: target.files[0]
});
}
upload() {
console.log(this.state.file);
const formData = new FormData();
formData.append('file', this.state.file);
formData.append('token', 'xxxxxxx');
let app = this;
axios.post('xxxx/supplier/public/qiniusave', formData).then(res => {
console.log(res);
app.setState({
imgUrl: res.data.data
});
})
}
render() {
return (
<div>
<h2>Home</h2>
<input type="file" onChange={this.fileChange} multiple/>
<button onClick={this.upload}>点击上传</button>
<div>
<img width={'45'} src={this.state.imgUrl} alt=""/>
</div>
</div>
);
}
}
本文地址:https://blog.csdn.net/u013239476/article/details/110247303
上一篇: 6章 性能平台GodEye源码分析-自定义拓展模块
下一篇: React如何创建组件