目錄
1.需求確定
2.具體內容
3.總結
1.需求確定
最近在項目中要點擊“幫助文檔”,下載《系統操作手冊》。
也就是獲取靜態資源文件export.pdf,將pdf文檔下載至本地。
拿到這個需求后,找了些方案,如下
方案1:在vue cli中安裝一些插件,如jquery,利用jquery下載本地文件;
方案2:直接使用原生ajax下載本地文件;
方案3:利用axios請求;
最后考慮到項目中已經在使用axios,就采用方案3。
2.具體內容
在使用過程中發現問題記錄如下:
項目1:vue 2.0 + element ui+es5中
利用a標簽,給個點擊事件download()
<a id="attname" class="attname" href="javascript:void(0);" @click="download">幫助文檔
頁面已經引用過axios,使用如下:
import axios from 'axios';
Download方法中為避免無法導出,將待導出文件名稱改為英文“export.pdf”,導出后的名稱設置為中文名稱“系統操作手冊.pdf”;
待導出文件放在“static”文件夾下;
download(){
axios.get('static/export.pdf', {
responseType: 'blob', //重要
}).then(response => {
const url = window.URL.createObjectURL(new Blob([response.data]));
const link = document.createElement('a');
let fname = '系統操作手冊.pdf';
link.href = url;
link.setAttribute('download', fname);
document.body.appendChild(link);
link.click();
});
}
項目2:vue 3.0 + iview ui+typescript中
利用a標簽,給個點擊事件download()
<a id="attname" class="attname" href="javascript:void(0);" @click="download">幫助文檔
頁面已經引用過axios
import axios from 'axios';
Download方法中為避免無法導出,將待導出文件名稱改為英文“export.pdf”,導出后的名稱設置為中文名稱“系統操作手冊.pdf”;
在“public”文件夾下建“export”文件夾,放待導出文件;
download(){
axios.get('export/export.pdf', {
responseType: 'blob', //重要
}).then(response => {
const url = window.URL.createObjectURL(new Blob([response.data]));
const link = document.createElement('a');
let fname = '系統操作手冊.pdf';
link.href = url;
link.setAttribute('download', fname);
document.body.appendChild(link);
link.click();
});
}
其中,在項目2的使用過程中遇到了問題,將待下載文件放在“static”或“assets”文件夾下,始終獲取不到待下載文件,不同的后綴的文件“.json、.ts”等都是404找不到,如下:
經過一天的問題查找,發現vue cli3.0中靜態資源文件夾為“public”,在“public”文件夾下建“export”文件夾,放待導出文件“export.pdf”后,返回狀態碼200,下載正常:
3.總結
vue cli2.0的靜態文件是static
vue cli3.0的靜態文件是public
童鞋們使用過程中千萬不要搞錯了,會獲取不到本地文件的
注:除本文中pdf文件外,還可下載其他格式為文件,使用方式類似;
記錄一下,以備查詢使用;