關於a標籤下載文件的問題

自己做的本地vue項目中想用a標籤進行文件的下載,href中填寫的是服務器的API


<div class="file-item" v-for="(item, index) in curTask.files" :key="index">
  <a class="file-name" :href="`/api/task/${curTask.id}/files/${item}`" :download="item">{{item}}</a>
</div>

但是點擊之後,顯示下載失敗,沒有發現文件。後臺是有設置header的,

response.setHeader("Content-disposition", "attachment;filename="+ file.name);

查看請求也發現沒有發出請求,沒有查到什麼解決方案。

於是只能通過axios請求文件的方式進行解決。

// vue頁面中

<a class="file-name" href="javascript:;" @click="download(item)">{{item}}</a>

// dowload 函數
async download(filename: string) {
    const data = await this.$store.dispatch(`task/${LOAD_FILE}`, {
      id: this.currentTask.id,
      filename
    });
    const url = URL.createObjectURL(data);
    const a = document.createElement('a'); // 生成一個a元素
    a.style.display = 'none';
    a.href = url;
    a.setAttribute('download', filename);
    a.click();
  }


// stores請求中

// httpRequestSilence 是項目中對axios接口進行的封裝
const { data } = await httpRequestSilence.get<IResponse<Blob> >(
`/tasks/${payload.id}/files/${payload.filename}`, 
{responseType: 'blob'});
if (data) {
    return Promise.resolve(data);
} else {
    return Promise.resolve('no file');
}

請求文件要注意的是需要設置返回的數據的類型爲Bolb,這樣才能拿到文件。

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章