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

前言

本次做后台管理系统,采用的是 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

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值