antd 里面的Upload图片上传
程序员文章站
2022-06-03 11:20:16
...
import React,{useState} from 'react';
import { Upload, Icon, message,Spin } from 'antd';
import serviceApi from '@/utils/api';
import {MessageTip} from '@/utils/tools.js'
import './upload.css'
// 上传单张图片
function getBase64(img, callback) {
const reader = new FileReader();
reader.addEventListener('load', () => callback(reader.result));
reader.readAsDataURL(img);
}
function beforeUpload(file) {
const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
if (!isJpgOrPng) {
message.error('仅支持JPG/PNG格式的图片');
}
const isLt2M = file.size / 1024 / 1024 < 2;
if (!isLt2M) {
message.error('图片大小不能超过 2MB!');
}
return isJpgOrPng && isLt2M;
}
const UploadAvatar = (props) =>{
const [loading,setLoading] = useState(false)
const [imageUrl,setImageUrl] = useState('')
const handleChange = info => {
if (info.file.status === 'uploading') {
setLoading(true)
return;
}
if (info.file.status === 'done') {
getBase64(info.file.originFileObj, imageUrl =>{
setLoading(false)
if(info.file.response.success){
const {module} = info.file.response // 返回的图片地址
props.childImg(module) // 传给父级的
setImageUrl(imageUrl)
MessageTip('success','文件上传成功')
}
});
}
};
const uploadButton = (
<div>
{
loading?<Spin />:''
}
<div className="ant-upload-text">Upload</div>
</div>
);
return (
<Upload
name="file"
listType="picture-card"
className="avatar-uploader"
showUploadList={false}
action={serviceApi.uploadFile}
data={{type:1}} // type 1图片 2试卷
beforeUpload={beforeUpload}
onChange={handleChange}
>
{imageUrl ? <img src={imageUrl} alt="avatar" style={{ width: '100%' }} /> : uploadButton}
</Upload>
);
}
export default UploadAvatar;
上一篇: LeetCode--33. 搜索旋转排序数组(C)
下一篇: centos7 docker 启动失败 报错【Job for docker.service failed because the control process exited with error】
推荐阅读
-
vue2.0 使用element-ui里的upload组件实现图片预览效果方法
-
基于vue-upload-component封装一个图片上传组件的示例
-
vue中使用axios post上传头像/图片并实时显示到页面的方法
-
vue中el-upload上传图片到七牛的示例代码
-
AntD框架的upload组件上传图片时遇到的一些坑
-
Vue+UpLoad实现上传预览和删除图片的实践
-
Vue+UpLoad实现上传预览和删除图片的实践
-
php5.6 上传图片error代码为6 或者 报错“PHP Warning: File upload error - unable to create a temporary file in Unknown on line 0”的解决办法
-
VUE 实现element upload上传图片到阿里云
-
用element的upload组件实现多图片上传和压缩的示例代码