项目有个地方要使用上传文件的功能,而且和element-ui不一样的是,并不是选择文件后立刻上传,而是点击按钮后才能上传。
代码:
// html
<el-upload
class="upload-demo"
action="file"
:auto-upload="false"
:on-remove="handleRemove"
:on-change="uploadChange"
:on-preview="handleClickEvent"
:file-list="upload['fileList']"
multiple
:limit="1"
accept=".pdf,.PDF"
:on-exceed="handleExceed">
<el-button size="small" type="primary">点击上传</el-button>
<div slot="tip" style="color:#f00;"><small>注:只支持.pdf文档格式,最大不超过5m。</small></div>
</el-upload>
action="file" 其实并没有file这个路径,写a,b,c都无所谓,但是好像不写还有点问题。
:on-preview="handleClickEvent" 这个方法是点击文件名触发的事件,这里是用来点击后下载文件的。
上传的文件file对象有个raw属性,这里面是文件的二进制数据,后端接口需要二进制数据,直接传这个raw给接口就行。
// js
handleRemove (file, fileList) {
console.log('handleRemove:', file)
this.upload.fileList = fileList
// this.$emit('deleteFileList', file, this.comIndex)
},
handleClickEvent(file) {
if (this.type !== 'view') {
return false
}
let obj = {
loading: 'NO'
}
console.log('handleUploadFile:', file)
api.pdfDownload({contractId: this.cid, ...obj}).then(res => {
this.downloadFile(res, file)
})
},
downloadFile (res, file) {
// type类型可以设置为文本类型,这里是pdf类型
this.pdfUrl = window.URL.createObjectURL(new Blob([res], { type: `application/pdf` }))
const link = document.createElement('a')
link.href = this.pdfUrl
link.setAttribute('download', file.name)
document.body.appendChild(link)
link.click()
},
handleExceed (files, fileList) {
this.$message.warning(`当前限制选择 1 个文件,本次选择了 ${files.length} 个文件,共选择了 ${files.length + fileList.length} 个文件`)
},
beforeRemove (file, fileList) {
return this.$confirm(`确定移除 ${file.name}?`)
},
uploadChange (file, fileList) {
// fileList 最后一个文件不能和前面的文件重名
const fileType = '.pdf,.PDF'
let fileName = file.name.substring(file.name.lastIndexOf('.') + 1)
if (fileType.indexOf(fileName) === -1) {
this.$message.error('不能选择该类型文件')
fileList.splice(fileList.length - 1, 1)
return false
} else {
let lastFile = fileList[fileList.length - 1].name
if (lastFile === null) {
fileList.splice(fileList.length - 1, 1)
}
for (let i = 0; i < fileList.length - 1; i++) {
if (lastFile === fileList[i].name) {
fileList.splice(fileList.length - 1, 1)
this.$message.error('不能重复选择上传文件')
break
}
}
this.upload.fileList = fileList
console.log('uploadChange:', file, this.upload.fileList)
}
},
本项目使用的是axios,如果想下载文件,还需要对请求做一些配置。
// 封装axios的http.js
interceptorInstance.interceptors.request.use(config => {
....
if (config.url.indexOf('/pdfDownload') !== -1) {
config.responseType = 'blob'
}
if (config.url.indexOf('/pdfDownload') !== -1) {
// 一定要设置响应类型,否则预览pdf加载为空白
config.responseType = 'arraybuffer'
// console.log("config.responseType = 'arraybuffer'")
}
......
}
网友评论