antd-vue上传自定义下载文件
功能需求:上传文件后,点击上传的文件可以打开图片格式的文件,pdf格式可以预览文档格式的文件。点击下载,下载时的文件名与上传时的文件名一致。问题:为解决后台可能上传同名文件,上传的文件覆盖了之前的文件。文件上传到服务器后,在文件名后添加一串随机字符串。这样接口返回给前端的url地址就会变成文件名+随机字符串。同时这导致前端出现一种情况:如果直接使用a-upload组件封装的点击事件下载文件,下载的文件名后面会有一串随机字符串。这不符合保证下载时文件名与上传一致的要求。为此,需要自定义a-upload的点击下载事件。现象:原因:a-upload组件上传文件后,自动生成a标签,点击文件时触发a标签的下载事件。如图解决:{{item.title}}:上传
constuploadList=ref([])//文件数组constfIndex=ref()//当前上传数据索引//uploadconstcustomRequest=file=>{constapi=uploadList[fIndex.value].apiconstmaxNum=uploadList[fIndex.价值]。maxNumconstformData=newFormData()formData.append('file',file.file)//去掉后缀指定文件名formData.append('fileName',file.file.name.substring(0,file.文件名.lastIndexOf('.')))//获取当前文件上传前的文件数constlistNum=uploadList[fIndex.value].fileList.lengthrequest.post(url,formData).then(res=>{if(res.result==0){//上传成功存储的urluploadList[fIndex.value].fileList[uploadList[fIndex.value].fileList.length-1].url=res.data.urlconstparams={url:res.data.url}request.post(api,params).then(result=>{if(result.result==0){file.onSuccess(res,file.file)//如果上传成功则检查是否超过文件数if(listNum>=maxNum){//文件数量超过删除第一个文件uploadList[fIndex.value].fileList.shift()}}else{message.error(result.message)uploadList[fIndex.value].fileList.splice(listNum,1)}uploadList[fIndex.value].loading=false}).catch(()=>{uploadList[fIndex.value].loading=false}).finally(()=>{//请求结束改变为最终状态uploadList[fIndex.value].loading=false})}else{uploadList[fIndex.value].fileList.splice(listNum,1)}}).catch(()=>{//上传失败uploadList[fIndex.value].fileList.splice(listNum,1)})}//上传前的事件constbeforeUpload=(file,fileList)=>{constsize=uploadList[fIndex.value].sizeconstmaxNum=uploadList[fIndex.value].maxNumconstfileLists=uploadList[fIndex.value].fileListconstisVerify=uploadList[fIndex.value].isVerifyconstaccept=uploadList[fIndex.value].acceptconstisLt=file.size/1024/1024
{constfiletype=file.name.split('.')[file.name.split('.').length-1]如果('.'+filetype==e){type=true}})if(!type){message.error('文件格式错误,请重新上传')fileList.pop()returnfalse}else{//验证文件数if(fileLists.length{//根据后缀文件的预览或下载操作.write(``)}elseif(item.name.endsWith('.pdf')){窗口.open(item.url+'?response-content-type=application/pdf')}else{if(item.url){downloadFile(item.url,item.name)}}}//下载的文件将返回后台文件将url链接转换为文件流格式,点击打开新窗口下载文件constdownloadFile=async(url,fileName=null)=>{consta=document.createElement('a')//创建一个标签if(fileName){constresponse=awaitfetch(url)//将内容转换为blob地址constblob=awaitresponse.blob()//创建一个隐藏的可下载链接constobjectUrl=window.URL.createObjectURL(blob)a.href=objectUrla.download=fileName}else{a.href=url}a.click()a.remove()}这样就可以按要求下载和预览文件了