一、
// 文件就在前端某個文件夾下面 downloadDocumentation() { let res = '@/download/SDK接口說明.docx'; // 文件的路徑 let fileName = 'SDK接口說明.docx'; // 下載過后的文件名 let url = window.URL.createObjectURL(new Blob([res])); let link = document.createElement('a'); link.style.display = 'none'; link.href = url; link.setAttribute('download', fileName);// 文件名 document.body.appendChild(link); link.click();// 觸發事件,下載文件 document.body.removeChild(link); // 下載完成移除元素 window.URL.revokeObjectURL(url); // 釋放掉blob對象 }
downloadDocumentation() { let filename = "SDK接口說明.docx"; this.$axios({ url: "http://localhost:8000/usecase/download/", method: 'get', params: {"filename": filename}, responseType: 'blob' // 處理返回的數據亂碼問題 }).then(response => { if (response.data.type === "application/json") { console.log("找不到文件"); } else { const blob = new Blob([response.data], {type: 'application/vnd.ms-excel;charset=utf-8'}); const link = document.createElement('a'); // 創建a鏈接,用於下載文件 link.download = filename; link.style.display = 'none'; link.href = URL.createObjectURL(blob); document.body.appendChild(link); link.click(); // 觸發事件,下載文件 URL.revokeObjectURL(link.href) ;// 釋放掉blob對象 document.body.removeChild(link) // 下載完成移除元素 } }) }
# 下載文件類 class DownloadFile: def __init__(self, filename): self.filename = filename self.filepath = 'download/' + self.filename def downloadfile(self): # 判斷是否存在此文件 if not os.path.exists(self.filepath): return False response = StreamingHttpResponse(open(self.filepath, 'rb')) # 以文件流的方式發開文件 response['content_type'] = "application/octet-stream" response['Content-Disposition'] = 'attachment' + os.path.basename(self.filepath) return response