gpt4 book ai didi

javascript - readAsDataURL 多图像上传 ReactJS

转载 作者:行者123 更新时间:2023-12-01 01:38:11 24 4
gpt4 key购买 nike

美好的一天,我如何更改我的代码,以便它接受带有预览的多个图像上传,并且用户可以删除和设置主图像。

顺便说一句,我的代码只允许上传一张图片。

这是我到目前为止所得到的:

_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>
);
}

非常感谢您的帮助。

最佳答案

要在 React 代码中上传图像,您需要将 state 中的每个路径转换为 ​​Array

然后适当改变setstate,在渲染组件时使用map函数循环遍历state。

这是我上传多个图像的代码,希望它能让您更好地了解它:

    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>
)
}

关于javascript - readAsDataURL 多图像上传 ReactJS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52641147/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com