antd Upload组建上传图片文件(开发笔记)
程序员文章站
2022-06-03 11:20:46
...
<Upload
name="file"//设置为上传是文件形式
listType="picture-card" //卡片的形式展示
className="avatar-uploader"
accept="image/jpeg,image/png"//设置仅仅支持扩展名为:.png/.jpg/.jpeg
customRequest={info => {//手动上传,自定义上传提交方式
const formData = new FormData();
formData.append('file', info.file);//名字和后端接口名字对应
fetch(http + "upload", {
method: 'post',
headers: {
"Authorization": localStorage.getItem("token"),
},
body: formData,
}).then(res => res.json())
.then(res => {
console.log(res)
if (res.code === 20000) {
message.success("文件上传成功!");
this.setState({
imageUrl: https + res.payload,
businessLicense: res.payload
})
}
}).catch(err => {
console.log(err)
})
}}
showUploadList={false}
beforeUpload={bdeforeUpload}
onChange={this.handleChange}
>
{imageUrl ? <img src={imageUrl} alt="avatar" style={{ width: '100%', height: "190px" }} /> : uploadDom}
</Upload>
beforeUpload
上传之前的钩子,参数为上传文件,该参数设置上传文件的类型。在utils工具类文件中封装,代码如下:
export const bdeforeUpload = (file) => {
// 限制上传文件类型
const imgType = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/jpg';
if (!imgType) {
message.warning("只能上传 JPG/PNG/JPEG 格式的图片!")
}
// 限制上传文件大小
const imgSize = file.size / 1024 / 1024 < 1;
if (!imgSize) {
message.warning("上传图片要小于1M")
}
return imgType && imgSize
}
onChange
文件上传改变时的状态,代码如下:
handleChange = (info) => {
console.log(info.file.name)
console.log(info)
if (info.file.status === 'uploading') {
this.setState({ fileName: info.file.name });
return;
}
if (info.file.status === 'done') {
getBase64(info.file.originFileObj, imageUrl =>
this.setState({
imageUrl: imageUrl,
fileName: info.file.name
}),
);
}
}
export const getBase64 = (img, callback) => {
const reader = new FileReader();
reader.addEventListener("load", () => callback(reader.result));
reader.readAsDataURL(img)
}