Example of downloading files with vue+django

Example of downloading files with vue+django

1. Overview

In 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 Project

This 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 project

Create 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:
  • How to use Vue to directly download files and modify file names through the URL connection of Alibaba Cloud OSS
  • Springboot+vue realizes page download file
  • Springboot+vue to realize file upload and download
  • Vue implements the complete front-end and back-end code for downloading file streams
  • Tutorial on how to batch download files/pictures in zip using Vue
  • vue - download and export file operations in the form of file stream blob
  • Use axios in vue to implement post method to obtain binary stream download file (example code)
  • Vue excel upload preview and table content download to excel file
  • Springboot integrates vue to upload and download files
  • Vue implements online preview of PDF files and downloading (pdf.js)
  • Vue implements the function of clicking a button to download files

<<:  Linux kernel device driver address mapping notes

>>:  Example of adding and deleting range partitions in MySQL 5.5

Recommend

Nginx operation and maintenance domain name verification method example

When configuring the interface domain name, each ...

Web2.0: Causes and Solutions of Information Overload

<br />Information duplication, information o...

Linux redis-Sentinel configuration details

download Download address: https://redis.io/downl...

Docker-compose image release process analysis of springboot project

Introduction The Docker-Compose project is an off...

Detailed explanation of Docker container network port configuration process

Exposing network ports In fact, there are two par...

XHTML Getting Started Tutorial: Using the Frame Tag

<br />The frame structure allows several web...

Mysql 5.6.37 winx64 installation dual version mysql notes

If MySQL version 5.0 already exists on the machin...

Example code showing common graphic effects in CSS styles

Let me briefly describe some common basic graphic...

Detailed explanation of MySQL's Seconds_Behind_Master

Table of contents Seconds_Behind_Master Original ...

Commonplace talk about the usage of MYSQL pattern matching REGEXP and like

like LIKE requires the entire data to match, whil...

How to solve the slow speed of MySQL Like fuzzy query

Question: Although the index has been created, wh...

Solution to MySQL remote connection failure

I have encountered the problem that MySQL can con...

Nginx monitoring issues under Linux

nginx installation Ensure that the virtual machin...

Detailed explanation of the basic usage of VUE watch listener

Table of contents 1. The following code is a simp...