vue+django實(shí)現(xiàn)下載文件的示例
一、概述
在項(xiàng)目中,點(diǎn)擊下載按鈕,就可以下載文件。
傳統(tǒng)的下載鏈接一般是get方式,這種鏈接是公開的,可以任意下載。
在實(shí)際項(xiàng)目,某些下載鏈接,是私密的。必須使用post方式,傳遞正確的參數(shù),才能下載。
二、django項(xiàng)目
本環(huán)境使用django 3.1.5,新建項(xiàng)目download_demo

安裝模塊
pip3 install djangorestframework django-cors-headers
修改文件download_demo/settings.py
INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'api.apps.ApiConfig', 'corsheaders', # 注冊應(yīng)用cors ]
注冊中間件
MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'corsheaders.middleware.CorsMiddleware', # 注冊組件cors ]
最后一行增加
# 跨域增加忽略 CORS_ALLOW_CREDENTIALS = True CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_METHODS = ( 'GET', 'OPTIONS', 'PATCH', 'POST', 'VIEW', ) CORS_ALLOW_HEADERS = ( 'XMLHttpRequest', 'X_FILENAME', 'accept-encoding', 'authorization', 'content-type', 'dnt', 'origin', 'user-agent', 'x-csrftoken', 'x-requested-with', 'Pragma', )
修改download_demo/urls.py
from django.contrib import admin
from django.urls import path
from api import views
urlpatterns = [
path('admin/', admin.site.urls),
path('download/excel/', views.ExcelFileDownload.as_view()),
]
修改api/views.py
from django.shortcuts import render,HttpResponse
from download_demo import settings
from django.utils.encoding import escape_uri_path
from django.http import StreamingHttpResponse
from django.http import JsonResponse
from rest_framework.views import APIView
from rest_framework import status
import os
class ExcelFileDownload(APIView):
def post(self,request):
print(request.data)
# filename = "大江大河.xlsx"
filename = request.data.get("filename")
download_file_path = os.path.join(settings.BASE_DIR, "upload",filename)
print("download_file_path",download_file_path)
response = self.big_file_download(download_file_path, filename)
if response:
return response
return JsonResponse({'status': 'HttpResponse', 'msg': 'Excel下載失敗'})
def file_iterator(self,file_path, chunk_size=512):
"""
文件生成器,防止文件過大,導(dǎo)致內(nèi)存溢出
:param file_path: 文件絕對路徑
:param chunk_size: 塊大小
:return: 生成器
"""
with open(file_path, mode='rb') as f:
while True:
c = f.read(chunk_size)
if c:
yield c
else:
break
def big_file_download(self,download_file_path, filename):
try:
response = StreamingHttpResponse(self.file_iterator(download_file_path))
# 增加headers
response['Content-Type'] = 'application/octet-stream'
response['Access-Control-Expose-Headers'] = "Content-Disposition, Content-Type"
response['Content-Disposition'] = "attachment; filename={}".format(escape_uri_path(filename))
return response
except Exception:
return JsonResponse({'status': status.HTTP_400_BAD_REQUEST, 'msg': 'Excel下載失敗'},
status=status.HTTP_400_BAD_REQUEST)
在項(xiàng)目根目錄創(chuàng)建upload文件

里面放一個excel文件,比如:大江大河.xlsx
三、vue項(xiàng)目
新建一個vue項(xiàng)目,安裝ElementUI 模塊即可。
新建test.vue
<template>
<div style="width: 70%;margin-left: 30px;margin-top: 30px;">
<el-button class="filter-item" type="success" icon="el-icon-download" @click="downFile()">下載</el-button>
</div>
</template>
<script>
import axios from 'axios'
export default {
data() {
return {
}
},
mounted: function() {
},
methods: {
downloadFile(url, options = {}){
return new Promise((resolve, reject) => {
// console.log(`${url} 請求數(shù)據(jù),參數(shù)=>`, JSON.stringify(options))
// axios.defaults.headers['content-type'] = 'application/json;charset=UTF-8'
axios({
method: 'post',
url: url, // 請求地址
data: options, // 參數(shù)
responseType: 'blob' // 表明返回服務(wù)器返回的數(shù)據(jù)類型
}).then(
response => {
// console.log("下載響應(yīng)",response)
resolve(response.data)
let blob = new Blob([response.data], {
type: 'application/vnd.ms-excel'
})
// console.log(blob)
// let fileName = Date.parse(new Date()) + '.xlsx'
// 切割出文件名
let fileNameEncode = response.headers['content-disposition'].split("filename=")[1];
// 解碼
let fileName = decodeURIComponent(fileNameEncode)
// console.log("fileName",fileName)
if (window.navigator.msSaveOrOpenBlob) {
// console.log(2)
navigator.msSaveBlob(blob, fileName)
} else {
// console.log(3)
var link = document.createElement('a')
link.href = window.URL.createObjectURL(blob)
link.download = fileName
link.click()
//釋放內(nèi)存
window.URL.revokeObjectURL(link.href)
}
},
err => {
reject(err)
}
)
})
},
// 下載文件
downFile(){
let postUrl= "http://127.0.0.1:8000/download/excel/"
let params = {
filename: "大江大河.xlsx",
}
// console.log("下載參數(shù)",params)
this.downloadFile(postUrl,params)
},
}
}
</script>
<style>
</style>
注意:這里使用post請求,并將filename傳輸給api,用來下載指定的文件。
訪問測試頁面,點(diǎn)擊下載按鈕

就會自動下載

打開工具欄,查看響應(yīng)信息

這里,就是django返回的文件名,瀏覽器下載保存的文件名,也是這個。
遇到中文,會進(jìn)行URLcode編碼。
所以在vue代碼中,對Content-Disposition做了切割,得到了文件名。
以上就是vue+django實(shí)現(xiàn)下載文件的示例的詳細(xì)內(nèi)容,更多關(guān)于vue+django實(shí)現(xiàn)下載文件的資料請關(guān)注腳本之家其它相關(guān)文章!
- Vue通過阿里云oss的url連接直接下載文件并修改文件名的方法
- springboot+vue實(shí)現(xiàn)頁面下載文件
- springboot+vue實(shí)現(xiàn)文件上傳下載
- vue實(shí)現(xiàn)下載文件流完整前后端代碼
- vue將文件/圖片批量打包下載zip的教程
- vue-以文件流-blob-的形式-下載-導(dǎo)出文件操作
- 在vue中使用axios實(shí)現(xiàn)post方式獲取二進(jìn)制流下載文件(實(shí)例代碼)
- vue excel上傳預(yù)覽和table內(nèi)容下載到excel文件中
- springboot整合vue實(shí)現(xiàn)上傳下載文件
- vue實(shí)現(xiàn)在線預(yù)覽pdf文件和下載(pdf.js)
- vue實(shí)現(xiàn)點(diǎn)擊按鈕下載文件功能
相關(guān)文章
vue中使用vue-seamless-scroll插件實(shí)現(xiàn)列表無縫滾動效果
這篇文章主要介紹了vue中使用vue-seamless-scroll插件無縫滾動,支持上下左右無縫滾動,單步滾動停留時間,以及水平方向的手動切換,需要的朋友可以參考下2022-06-06
vue 解決form表單提交但不跳轉(zhuǎn)頁面的問題
今天小編就為大家分享一篇vue 解決form表單提交但不跳轉(zhuǎn)頁面的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-10-10
Element的el-tree控件后臺數(shù)據(jù)結(jié)構(gòu)的生成以及方法的抽取
這篇文章主要介紹了Element的el-tree控件后臺數(shù)據(jù)結(jié)構(gòu)的生成以及方法的抽取,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-03-03
vue中各選項(xiàng)及鉤子函數(shù)執(zhí)行順序詳解
今天小編就為大家分享一篇vue中各選項(xiàng)及鉤子函數(shù)執(zhí)行順序詳解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-08-08
vue3.0實(shí)現(xiàn)點(diǎn)擊切換驗(yàn)證碼(組件)及校驗(yàn)
這篇文章主要為大家詳細(xì)介紹了vue3.0實(shí)現(xiàn)點(diǎn)擊切換驗(yàn)證碼(組件)及校驗(yàn),文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2020-11-11
vue開發(fā)之LogicFlow自定義業(yè)務(wù)節(jié)點(diǎn)
這篇文章主要為大家介紹了vue開發(fā)之LogicFlow自定義業(yè)務(wù)節(jié)點(diǎn),有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-01-01

