DJango + Vue 文件下载
后端
import requests from django.http import FileResponse from django.utils.encoding import escape_uri_path def download_file(request): if request.method == 'GET': ############ 文件在服务器本地 ############ # file_name = 'xxx.zip' # file_path = os.path.join(target_dir,file_name) # file = open(file_path,'rb') # response = FileResponse(file) ############ 文件通过第三方接口获取 ############ # 获取接口入参 params = json.loads(request.body) downloadUrl = params['downloadUrl'] file_name = params['file_name'] # 代理设置 proxies = { 'http':'http://ip:port', 'https':'https://ip:port', } # 创建会话并更新代理配置 session = requsets.Session() sesseion.proxies.update(proxies) session.keey_alive = False # 访问下载链接 res = session.get(downloadUrl) seeesion.close() response = FileResponse(res) # 设置响应内容类型和配置 response['Content-Type'] = 'applicatino/octet-stream' response['Content-Disposition'] = "attachment; filename=utf-8''{}".format(escape_uri_path(file_name)) # 处理文件名为中文 return response
前端
// xxx.vue import { DownloadFile } from '@/xxx/xxx' ... methods:{ ..., clickDownload(row) { const url = row.downloadUrl.split(',')[0] const temp = url.split('/') const file_name = temp[temp.length -1] const params = { downloadUrl: url, file_name: file_name, } this.$set(row,'loadingDownload',true) // 给按钮加上loading动效 DownloadFile(params, { responseType: 'blob', // 设置响应类型为Blob timeout: 50000, // 延长响应超时时间 }).then((res) => { // 使用blob对象接受文件流 let blob = new Blob([res],{ type: 'zip', }) // 隐秘创建一个下载链接并点击下载 let elink = document.createElement('a') elink.download = file_name elink.style.display = 'none' elink.href = window.URL.createObjectURL(blob) // 创建Blob链接 document.body.appendChild(elink) elink.click() // 删除链接 document.removeChild(elink) window.URL.revokeObjectURL(elink.href) // 销毁Blob链接 this.$set(row,'loadingDownload',true) // 给按钮关闭loading动效 }) }, } // xxx/xxx/xxx.js import request from '@/utils/request' export cont DownloadFile = (params,config) => request.post('url',{ ...params },{ ...config })
本文作者:注入灵魂
本文链接:https://www.cnblogs.com/totopian/p/16851499.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步