前后端文件流式传输

一、前端下载本地文件

// 文件就在前端某个文件夹下面
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

 

posted on 2020-05-20 19:05  软饭攻城狮  阅读(4841)  评论(0编辑  收藏  举报

导航