Vue implements file upload and download functions

Vue implements file upload and download functions

This article example shares the specific code of Vue to implement file upload and download functions for your reference. The specific content is as follows

1. a tag download attribute

In H5, a download attribute is added to the a tag to directly download the file, and the file name is the download attribute file name.

  • The download attribute currently only supports Google Chrome and Mozilla Firefox. Other browsers do not support this attribute.
  • Download is a new attribute in H5. H5 did not have this attribute before.

2. URL.createObjectURL

The URL.createObjectURL() method creates a URL pointing to the parameter object based on the passed parameters. The life of this URL only exists in the document in which it is created. The new object URL points to the executed File object or Blob object.

A File object is a file. For example, if I use the input type="file" tag to upload files, then each file in it is a File object.

Blob object is binary data. For example, the object created by new Blob() is a Blob object. For example, in XMLHttpRequest, if the responseType is specified as blob, the return value is also a blob object.

let URL = window.URL || window.webkitURL;
let downloadUrl = URL.createObjectURL(blob || file);

3. URL.revokeObjectURL

The URL.revokeObjectURL() method releases an object URL created by URL.createObjectURL(). If the object is no longer needed, it must be released. After being released, the object URL no longer points to the specified file.

downloadUrl && URL.revokeObjectURL(downloadUrl);

4. Upload and download files with Vue.js

<template>
    <div class="btn-box">
        <h3>File upload:</h3>
        <input class="file-input" type="file" @change="getFile($event)" />
        <el-button type="primary" @click="upload">Upload file (POST)</el-button>
        <h3>File Download:</h3>
        <el-button type="primary" @click="downloadLink">Download the linked file (window.open)</el-button>
        <el-button type="primary" @click="downloadBlobByGet">Binary stream download (GET)</el-button>
        <el-button type="primary" @click="downloadBlobByPost">Binary stream download (POST)</el-button>
    </div>
</template>
 
<script>
    import axios from "axios"
    export default {
        name: "attendPoint",
        data() {
            return {,
                file: null,
                fileName: "test.xlsx"
            }
        },
        methods: {
            // Select file getFile(event) {
                this.file = event.target.files[0];
            },
 
            // Upload file (POST)
            upload() {
                let url = "http://localhost:3000/upload/test";
                let formData = new FormData();
                formData.append("name", "zhangsan");
                formData.append("age", "18");
                formData.append("file", this.file);
                let config = {
                    headers: {
                        "Content-Type": "multipart/form-data"
                    }
                }
                axios.post(url, formData, config).then((res) => {
                    this.fileName = res.data.downloadUrl;
                    this.$message.success("Upload successful!");
                }).catch(() => {
                    this.$message.error("Please upload the file first!");
                })
            },
 
            // Download the file with link (window.open)
            downloadLink() {
                if (this.fileName) {
                    window.open("http://localhost:3000/download/test?fileName=" + this.fileName);
                }
            },
 
            //Binary stream download (GET)
            async downloadBlobByGet() {
                let urlGet = "http://localhost:3000/download/test?fileName=" + this.fileName;
                let fileData = await axios.get(urlGet, { responseType: "blob" });
                let URL = window.URL || window.webkitURL;
                let downloadUrl = URL.createObjectURL(fileData.data);
                let a = document.createElement("a");
                a.href = downloadUrl;
                a.download = this.fileName; //File name after downloading a.click();
                a = null;
                downloadUrl && URL.revokeObjectURL(downloadUrl);
            },
 
            //Binary stream download (POST)
            async downloadBlobByPost() {
                let urlPost = "http://localhost:3000/download/post/test";
                let fileData = await axios({
                    method: "post",
                    url: urlPost, // request address data: { fileName: this.fileName }, // parameter responseType: "blob" // indicates the data type returned by the server })
                let URL = window.URL || window.webkitURL;
                let downloadUrl = URL.createObjectURL(fileData.data);
                let a = document.createElement("a");
                a.download = this.fileName;
                a.href = downloadUrl;
                a.click();
                a = null;
                downloadUrl && URL.revokeObjectURL(downloadUrl);
            },
        },
    }
</script>
 
<style scoped>
    .btn-box {
        padding: 20px;
    }
    .el-button,
    input {
        max-width: fit-content;
        display: block;
        margin: 20px;
    }
</style>

The above is the full content of this article. I hope it will be helpful for everyone’s study. I also hope that everyone will support 123WORDPRESS.COM.

You may also be interested in:
  • Vue implements file upload and download
  • Springboot+vue to realize file upload and download
  • Vue excel upload preview and table content download to excel file
  • Springboot integrates vue to upload and download files
  • Vue implements file upload, reading and download functions
  • Two ways to implement Excel file upload and download functions in Vue
  • vue-cli+axios realizes file upload and download function (download receiving background returns file stream)

<<:  Detailed explanation of the usage and function of MySQL cursor

>>:  Centos7 mysql database installation and configuration tutorial

Recommend

Vue uses GraphVis to develop an infinitely expanded relationship graph

1. Go to the GraphVis official website to downloa...

jQuery plugin to implement minesweeper game (3)

This article shares the third article on how to u...

Introduction to the process of building your own FTP and SFTP servers

FTP and SFTP are widely used as file transfer pro...

Docker image export, import and copy example analysis

The first solution is to push the image to a publ...

Reasons and solutions for failure to insert emoji expressions in MySQL

Failure Scenario When calling JDBC to insert emoj...

How to use docker to deploy Django technology stack project

With the popularity and maturity of Docker, it ha...

How to fix the footer at the bottom of the page (multiple methods)

As a front-end Web engineer, you must have encoun...

Understanding the CSS transform-origin property

Preface I recently made a fireworks animation, wh...

Detailed explanation of jQuery's core functions and event handling

Table of contents event Page Loading Event Delega...

Customization Method of Linux Peripheral File System

Preface Generally speaking, when we talk about Li...

Vue implements div wheel zooming in and out

Implement div wheel zooming in and out in Vue pro...

MySQL table and column comments summary

Just like code, you can add comments to tables an...