后端
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 })
标签:Vue,elink,name,xxx,request,DJango,params,file,下载
From: https://www.cnblogs.com/totopian/p/16851499.html