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

How to change the character set encoding to UTF8 in MySQL 5.5/5.6 under Linux

1. Log in to MySQL and use SHOW VARIABLES LIKE &#...

The pitfall record of case when judging NULL value in MySQL

Table of contents Preface Mysql case when syntax:...

Implementation of MySQL master-slave status check

1. Check the synchronization status of A and B da...

Vue component library ElementUI implements table loading tree data tutorial

ElementUI implements a table tree list loading tu...

Example of JSON output in HTML format (test interface)

To display the JSON data in a beautiful indented ...

Introduction and examples of hidden fields in HTML

Basic syntax: <input type="hidden" na...

Docker Gitlab+Jenkins+Harbor builds a persistent platform operation

CI/CD Overview CI workflow design Git code versio...

Detailed explanation of mktemp, a basic Linux command

mktemp Create temporary files or directories in a...

Detailed explanation of the background-position percentage principle

When I was helping someone adjust the code today,...

Alpine Docker image font problem solving operations

1. Run fonts, open the font folder, and find the ...

Example code for implementing stacked carousel effect with HTML+CSS+JS

Effect: When the slideshow moves in one direction...

TypeScript decorator definition

Table of contents 1. Concept 1.1 Definition 1.2 D...

The past two years with user experience

<br />It has been no more than two years sin...

In-depth understanding of the use of the infer keyword in typescript

Table of contents infer Case: Deepen your underst...