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
When configuring the interface domain name, each ...
<br />Information duplication, information o...
css-vars-ponyfill When using CSS variables to ach...
download Download address: https://redis.io/downl...
Introduction The Docker-Compose project is an off...
Exposing network ports In fact, there are two par...
<br />The frame structure allows several web...
If MySQL version 5.0 already exists on the machin...
Let me briefly describe some common basic graphic...
Table of contents Seconds_Behind_Master Original ...
like LIKE requires the entire data to match, whil...
Question: Although the index has been created, wh...
I have encountered the problem that MySQL can con...
nginx installation Ensure that the virtual machin...
Table of contents 1. The following code is a simp...