1. OverviewIn the project, click the download button to download the file. Traditional download links are generally get links, which are public and can be downloaded at will. In actual projects, some download links are private. You must use the post method and pass the correct parameters to download. 2. Django ProjectThis environment uses Django 3.1.5, and creates a new project download_demo Installing the Module pip3 install djangorestframework django-cors-headers Modify the file 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', # Register application cors ] Registering middleware 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', # Register component cors ] The last line adds #Cross-domain addition ignores 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', ) Modify 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()), ] Modify 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 = "Big River.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 download failed'}) def file_iterator(self,file_path, chunk_size=512): """ File generator, to prevent the file from being too large and causing memory overflow:param file_path: absolute file path:param chunk_size: chunk size:return: generator """ 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)) # Add 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 download failed'}, status = status.HTTP_400_BAD_REQUEST) Create an upload file in the project root directory Put an excel file in it, for example: Great Rivers.xlsx 3. Vue projectCreate a new vue project and install the ElementUI module. Create a new 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()">Download</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} request data, parameters=>`, JSON.stringify(options)) // axios.defaults.headers['content-type'] = 'application/json; charset=UTF-8' axios({ method: 'post', url: url, // request address data: options, // parameter responseType: 'blob' // indicates the data type returned by the server}).then( response => { // console.log("Download response",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' // Cut out the file name let fileNameEncode = response.headers['content-disposition'].split("filename=")[1]; // Decoding 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() //Release memory window.URL.revokeObjectURL(link.href) } }, err => { reject(err) } ) }) }, // Download file downFile(){ let postUrl = "http://127.0.0.1:8000/download/excel/" let params = { filename: "Big River.xlsx", } // console.log("download parameters",params) this.downloadFile(postUrl,params) }, } } </script> <style> </style> Note: A post request is used here, and the filename is transmitted to the API to download the specified file. Visit the test page and click the download button It will automatically download Open the toolbar to view the response information Here, this is the file name returned by Django, and the file name downloaded and saved by the browser is also this. When Chinese characters are encountered, they will be encoded with URLcode. So in the vue code, Content-Disposition is cut and the file name is obtained. The above is the details of the example of vue+django to download files. For more information about vue+django to download files, please pay attention to other related articles on 123WORDPRESS.COM! You may also be interested in:
|
<<: Linux kernel device driver address mapping notes
>>: Example of adding and deleting range partitions in MySQL 5.5
I encountered this problem when I was making the ...
Table of contents UI Design Echarts example effec...
After installing a centos8 service under vmware a...
MySQL installation (4, 5, 6 can be omitted) State...
List style properties There are 2 types of lists ...
The domestic market still has a certain demand fo...
XML files should be encoded in utf-8 as much as p...
Table of contents Introduction Using Strict mode ...
This article example shares the specific code of ...
Recently, I encountered a database with the follo...
Only show the top border <table frame=above>...
Copy code The code is as follows: wmode parameter...
Create a mysql user and authorize: Format: grant ...
Generic load/write methods Manually specify optio...
It is very convenient to configure virtual host v...