<input
type="file"
multiple
ref={(ref) => (this.fileInputRef = ref)}
onChange={this.handleFileUpload}
style={{display:'none'}}
accept="image/*"
/>
<button ref={(ref) => (this.uploadBtn = ref)} onClick={() => this.uploadImg()}>图片上传</button>
// 上传
uploadImg = ()=>{
this.fileInputRef.click();
}
// 转换成base64
getBase64 = (file) =>
new Promise((resolve, reject) => {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => resolve(reader.result);
reader.onerror = (error) => reject(error);
});
handleFileUpload = async (e) => {
const file = e.target.files;
// 原图片列表
const { sourceList } = this.state;
const data = await this.ergodicFun(file,sourceList);
data.forEach(async item =>{
item.picBase = await item.picBase
})
this.setState({
sourceList: [...sourceList,...data]
})
};
ergodicFun = (file,sourceList)=>{
return Object.values(file).map( (value,index) => {
const baseFile = this.getBase64(value);
return {
picName:value.name,//图片名
picOrder: sourceList.length + index + 1,//图片顺序
picBase: baseFile
};
})
}