【问题描述】:使用Upload组件时,默认不显示下载图标不能下载上传的文件。
【要 求】:增加上传文件的下载。
在组件的props属性中增加showUploadList: { showDownloadIcon: true },这样就显示下载图标了。
官方解释 showUploadList是否展示文件列表, 可设为一个对象,用于单独设定 showPreviewIcon
, showRemoveIcon
和 showDownloadIcon
还要增加下载处理方法onDownload: this.onDownload。
最后对下载处理方法进行实现。
import React, { PureComponent, Fragment } from 'react';
import { Upload, message, Button, Icon } from 'antd';
class UploadFile extends PureComponent {
constructor(props) {
super(props);
this.state = {
fileList: null,
};
}
componentDidMount() {}
handleChange = info => {
};
beforeUpload = file => {
};
onDownload = file => {
let attachId = file&&file.attachId,
//need-download=1必须添加,不加的话txt pdf等不会下载而是直接打开
let url =
localStorage.getItem('severUrl') +
'XXXX?id=' +
attachId +
'&need-download=1';
//获得id为downLoadListFrame的frame
var divFrame = window.parent.document.getElementById('downLoadListFrame');
//判断是否存在,如果存在先移除,再重新创建
if (divFrame != null) {
window.parent.document.body.removeChild(divFrame);
}
var iframe = document.createElement('iframe');
iframe.setAttribute('id', 'downLoadListFrame');
iframe.src = url;
document.body.appendChild(iframe);
// 不加下面语句会自动下载2次---不是很理解
setTimeout(function() {
iframe.src = '';
}, 1000);
};
render() {
const props = {
name: 'file',
action:'上传文件地址',
onChange: this.handleChange,
accept: '文件格式的限制',
fileList: this.state.fileList,
beforeUpload: this.beforeUpload,
data: { 附带的一些参数 },
onDownload: this.onDownload,
showUploadList: { showDownloadIcon: true },
};
return (
<Upload {...props}>
<Button >
<Icon type="upload" /> 文件上传
</Button>
</Upload>
);
}
}
export default UploadFile;