antd upload手动上传_前端AntD框架的upload组件上传图片时遇到的一些坑

本文介绍了在使用AntD框架的Upload组件进行图片上传时遇到的若干问题,包括图片预览导致浏览器卡死,以及如何处理上传前的格式校验和编辑已有页面时的图片管理。提供了详细的代码示例,展示了如何解决图片base64编码过大导致的预览卡顿问题,以及在redux中处理默认图片数据的方法。
摘要由CSDN通过智能技术生成

前言

本次做后台管理系统,采用的是 AntD 框架。涉及到图片的上传,用的是AntD的 upload 组件。

前端做文件上传这个功能,是很有技术难度的。既然框架给我们提供好了,那就直接用呗。结果用的时候,发现 upload 组件的很多bug。下面来列举几个。

备注:本文写于2019-03-02,使用的 antd 版本是 3.13.6。

使用 AntD 的 upload 组件做图片的上传

因为需要上传多张图片,所以采用的是照片墙的形式。上传成功后的界面如下:

(1)上传中:

(2)上传成功:

(3)图片预览:

按照官方提供的实例,特此整理出项目开发中的完整写法,亲测有效。代码如下:

/* eslint-disable */

import { Upload, Icon, Modal, Form } from 'antd';

const FormItem = Form.Item;

class PicturesWall extends PureComponent {

state = {

previewVisible: false,

previewImage: '',

imgList: [],

};

handleChange = ({ file, fileList }) => {

console.log(JSON.stringify(file)); // file 是当前正在上传的 单个 img

console.log(JSON.stringify(fileList)); // fileList 是已上传的全部 img 列表

this.setState({

imgList: fileList,

});

};

handleCancel = () => this.setState({ previewVisible: false });

handlePreview = file => {

this.setState({

previewImage: file.url || file.thumbUrl,

previewVisible: true,

});

};

// 参考链接:https://www.jianshu.com/p/f356f050b3c9

handleBeforeUpload = file => {

//限制图片 格式、size、分辨率

const isJPG = file.type === 'image/jpeg';

const isJPEG = file.type === 'image/jpeg';

const isGIF = file.type === 'image/gif';

const isPNG = file.type === 'image/png';

if (!(isJPG || isJPEG || isGIF || isPNG)) {

Modal.error({

title: '只能上传JPG 、JPEG 、GIF、 PNG格式的图片~',

});

return;

}

const isLt2M = file.size / 1024 / 1024 < 2;

if (!isLt2M) {

Modal.error({

title: '超过2M限制,不允许上传~',

});

return;

}

return (isJPG || isJPEG || isGIF || isPNG) && isLt2M && this.checkImageWH(file);

};

//返回一个 promise:检测通过则返回resolve;失败则返回reject,并阻止图片上传

checkImageWH(file) {

let self = this;

return new Promise(function(resolve, reject) {

let filereader = new FileReader();

filereader.onload = e => {

let src = e.target.result;

const image = new Image();

image.onload = function() {

// 获取图片的宽高,并存放到file对象中

console.log('file width :' + this.width);

console.log('file height :' + this.height);

file.width = this.width;

file.height = this.height;

resolve();

};

image.onerror = reject;

image.src = src;

};

filereader.readAsDataURL(file);

});

}

handleSubmit = e => {

const { dispatch, form } = this.props;

e.preventDefault();

form.validateFieldsAndScroll((err, values) => {// values 是form表单里的参数

// 点击按钮后,将表单提交给后台

dispatch({

type: 'mymodel/submitFormData',

payload: values,

});

});

};

render() {

const { previewVisible, previewImage, imgList } = this.state; // 从 state 中拿数据

const uploadButton = (

Upload

);

return (

{getFieldD

Ant Design中的Upload组件可以通过设置`showUploadList`属性为`false`,然后使用自定义的进度条组件来实现上传进度的显示。 以下是一个上传大文件并显示进度条进度的示例代码: ```jsx import { Upload, Button } from 'antd'; import { UploadOutlined } from '@ant-design/icons'; import React, { useState } from 'react'; const UploadProgress = ({ percent }) => ( <div style={{ margin: '10px 0' }}> <div style={{ width: `${percent}%`, height: '5px', backgroundColor: '#1890ff' }}></div> </div> ); const Demo = () => { const [uploading, setUploading] = useState(false); const [progress, setProgress] = useState(0); const handleUpload = ({ file }) => { const formData = new FormData(); formData.append('file', file); setUploading(true); // 模拟上传进度 const timer = setInterval(() => { setProgress((prevProgress) => { if (prevProgress >= 100) { clearInterval(timer); setUploading(false); return 100; } else { return prevProgress + 10; } }); }, 500); // 发送上传请求 // axios.post('/api/upload', formData) // .then(() => { // clearInterval(timer); // setUploading(false); // }) // .catch(() => { // clearInterval(timer); // setUploading(false); // }); }; return ( <Upload name="file" action="/api/upload" showUploadList={false} beforeUpload={() => false} onChange={() => {}} customRequest={handleUpload} > <Button icon={<UploadOutlined />} disabled={uploading}> {uploading ? '上传中' : '点击上传'} </Button> {uploading && <UploadProgress percent={progress} />} </Upload> ); }; export default Demo; ``` 这段代码中,我们定义了一个`UploadProgress`组件作为自定义的进度条组件,它接受一个`percent`属性用来表示上传进度的百分比。在`handleUpload`函数中,我们使用`setInterval`模拟上传进度,并使用`setProgress`函数更新上传进度。当上传进度达到100,我们清除定器并将`uploading`状态设置为`false`,表示上传完成。在`Upload`组件中,我们将`showUploadList`属性设置为`false`,禁用默认的上传列表,然后使用自定义的按钮和进度条组件来替代默认的上传按钮和上传进度条。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值