file.substring()
<div class="file_list" v-for="(i, index) in fileList" :key="index">
<div class="file_info">
<img v-if="i.http.substring(i.http.length - 3) === 'jpg' || i.http.substring(i.http.length - 4) === 'jpeg'" src="../taskSend/img/jpg.png" alt=""/>
<img v-if="i.http.substring(i.http.length - 3) === 'mp4'" src="../taskSend/img/video.png" alt="" />
<img v-if="i.http.substring(i.http.length - 3) === 'pdf'" src="../taskSend/img/pdf.png" alt="" />
<img v-if="i.http.substring(i.http.length - 3) === 'doc'" src="../taskSend/img/word.png" alt="" />
<img v-if="i.http.substring(i.http.length - 4) === 'docx'" src="../taskSend/img/word.png" alt="" />
<div>{{ i.fileName }}</div>
</div>
<span class="file_show" @click="showFile(i.http)" style="margin-left:-60px">查看</span>
<span @click="downloadFile(i.http,i.fileName)" class="file_show">下载</span>
</div>
参数
http
指定文件在服务器上的路径,参数fileName
指定下载后文件的文件名。函数体内部创建了一个新的链接
link
,将该链接的CSS样式属性中的display
设置为none
,使其不在页面上显示。将链接的
href
属性设为服务器上的文件路径,将download
属性设置为文件名,表示该链接指向的文件可以被下载。将链接添加到页面(
document.body
),并且将链接触发了一个点击操作,即将click
事件调用link.click()
函数。这样做会直接跳转到该文件的下载地址,使用浏览器提供的下载功能将文件下载到本地。在实际项目中,可以使用JavaScript的
XMLHttpRequest
对象在后台进行异步的文件下载,也可以使用Vue的axios
库进行文件下载。
/** 下载按钮操作 */
downloadFile(http,fileName) {
console.log(this.fileList);
let link = document.createElement("a");
link.style.display = "none";
link.href = '/dev-api' + http
link.setAttribute("download", fileName);
document.body.appendChild(link);
link.click();
},