感觉今天有些不熟悉的技术栈做起来要整死人
做个React的文件上传差点把人搞死了
<div className="Plan-files-box">
<span style={{ marginRight: "5px", verticalAlignChange: 'top' }}> 预览文件 </span>
<Upload
accept='.doc,.docx,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document'
beforeUpload={this.avatarBeforeUpload}
multiple={true}
customRequest={this.customRequest}
className='upload-list-inline'
onRemove={this.onRemoveFile}
fileList={this.state.newFileList}
onDownload={this.onDownloadFile}
>
<Button className='btn-add-import'>
<svg aria-hidden="true" className="example">
<use xlinkHref="#icondaoru" />
</svg>导入文件
</Button>
</Upload>
<Button className="Download-entire" onClick={this.onDownloadFileAll}>下载全部</Button>
<p className="size-title">支持文件格式: .doc、.docx、.pdf,单个文件不能超过2MB</p>
</div>
avatarBeforeUpload = (file) => {
let fileName = file.name.split('.');
const fileType = fileName.slice(-1)[0];
const isJPG = (fileType === 'doc') || (fileType === 'docx') || (fileType === 'pdf');
if (!isJPG) {
message.error('仅支持文件格式:.doc、.docx、.pdf格式附件!')
}
const isLt1M = file.size / 1024 / 1024 < 2;
if (!isLt1M) {
message.error('附件大小不能超过2MB!');
}
return isJPG && isLt1M;
};
// 可以自定义自己的上传实现
customRequest = (file) => {
this.setState({
loadingUplaod: true
})
let form = new FormData()
form.append('file', file.file)
axios.post(BaseURL + "/data/emergencyPlan/uploadFile", form)
.then((response) => {
if (response.status === 200) {
let fileData = file.file
let newFile = {
...fileData,
url: response.data.data.split("=")[0],
completeUrl: response.data.data,
name: response.data.data.split("=")[1]
}
this.setState({
loadingUplaod: false,
newFileList: [...this.state.newFileList, newFile],
downloadList: [...this.state.downloadList, {
name: response.data.data.split("=")[1],
url: response.data.data.split("=")[0]
}]
})
}
})
.catch(function (error) {
console.log(error);
});
}
// 文件删除
onRemoveFile = (file) => {
const resFile = file.url ? file.url : ""
return axios({
url: BaseURL + "/data/emergencyPlan/delFile",
method: "DELETE",
params: {
urlStr: resFile
}
}).then((res) => {
const { code, msg } = res.data
let list = this.state.newFileList.filter(item => item.url !== file.url)
if (code === 100) {
this.setState({
newFileList: list
})
message.success(msg || '删除成功')
} else {
message.error(msg || '删除失败')
}
})
}
// 上传之前的方法
avatarBeforeUpload = (file) => {
let fileName = file.name.split('.');
const fileType = fileName.slice(-1)[0];
const isJPG = (fileType === 'doc') || (fileType === 'docx') || (fileType === 'pdf');
if (!isJPG) {
message.error('仅支持文件格式:.doc、.docx、.pdf格式附件!')
}
const isLt1M = file.size / 1024 / 1024 < 2;
if (!isLt1M) {
message.error('附件大小不能超过2MB!');
}
return isJPG && isLt1M;
};
// 下载全部文件
onDownloadFileAll = () => {
const { newFileList } = this.state;
let timeUp = 0;
for (let i = 0; i < newFileList.length; i++) {
timeUp += i;
const name = newFileList[i].name
const url = newFileList[i].url
setTimeout(() => {
this.download(name, url)
}, timeUp * 100);
}
}
实际截图:
image.png
网友评论