前后端文件流式傳輸


一、前端下載本地文件

// 文件就在前端某個文件夾下面
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對象
}

二、前后端文件流式文件傳輸

2.1 前端

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) // 下載完成移除元素
        }
    })
}

2.2 后端

# 下載文件類
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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM