早上好,我该如何更改代码,以便它接受带有预览的多张图片上传,并且用户可以删除和设置主图片。
我的代码仅允许上传一张图像。
这是到目前为止我得到的:
_handleImageChange(e) {
e.preventDefault();
let reader = new FileReader();
let file = e.target.files;
console.log('file', file);
console.log('reader', reader);
reader.onloadend = () => {
this.setState({
file: file,
imagePreviewUrl: reader.result
});
this.props.onImageChange(this.state);
}
reader.readAsDataURL(file);
}
render(){
let { imagePreviewUrl } = this.state;
let $imagePreview = null;
let path = Config.PROJECT_PATH + '' + Config.IMAGE.PATH + '' + this.props.imageModule + '/thumb/' + this.props.image;
if (imagePreviewUrl) {
$imagePreview = (<ThumbImage image={imagePreviewUrl} ref='myImage'/>);
}
else{
if (this.props.image) {
$imagePreview = (<ThumbImage image={path} />);
}
else{
$imagePreview = (<ThumbImage image={defaultImage} />);
}
}
return(
<div>
<div className="modal-image-preview">
{ $imagePreview }
</div>
<div className="modal-image-button">
<form onSubmit={(e)=>this._handleSubmit(e)}>
<RaisedButton style= {{ backgroundColor: '#000' }} containerElement='image' label="Choose an Image" labelPosition="before" onChange={(e)=>this._handleImageChange(e)}>
<input type="file" style={styles.imageInput} multiple/>
</RaisedButton>
</form>
</div>
</div>
);
}
非常感谢您的帮助。
答案 0 :(得分:1)
要以您的反应代码上传图像,您需要进入状态中的每个路径,以阵列
然后正确更改setstate,在渲染组件时使用map函数遍历状态。
这是我用于上传多张图片的代码,希望它能为您提供更好的主意:
constructor(props) {
super(props);
this.state = {
files: [],
imagesPreviewUrls: []
};
this._handleImageChange = this._handleImageChange.bind(this);
this._handleSubmit = this._handleSubmit.bind(this);
}
_handleSubmit(e) {
//Sumbit handler
e.preventDefault();
const formData = new FormData();
formData.append('image', this.state.file);
axios.get('/api/upload', formData)
.then(response => { console.log(response) });
}
_handleImageChange(e) {
e.preventDefault();
let files = Array.from(e.target.files);
files.forEach((file) => {
let reader = new FileReader();
reader.onloadend = () => {
this.setState({
files: [...this.state.files, file],
imagesPreviewUrls: [...this.state.imagesPreviewUrls, reader.result]
});
}
reader.readAsDataURL(file);
});
}
render() {
return (
<div>
<form onSubmit={this._handleSubmit}>
<input className="upload" type="file" accept='image/*' onChange={this._handleImageChange} multiple/>
<button type="submit" onClick={this._handleSubmit}>Upload Image</button>
{this.state.imagesPreviewUrls.map((imagePreviewUrl) => {
return <img key={imagePreviewUrl} alt='previewImg' src={imagePreviewUrl} />
})}
</form>
</div>
)
}