Vue realizes file upload and download function

  • 2021-11-24 00:27:51
  • OfStack

This article example for everyone to share the Vue file upload and download function of the specific code, for your reference, the specific content is as follows

1. a tag download attribute

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

The download attribute only supports Google Chrome and Mozilla Firefox for the time being, and other browsers do not support this attribute; download is a new attribute of H5, which was not available before H5;

2. URL. createObjectURL

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

File object is a file. For example, if I upload a file with input type = "file" tag, each file in it is an File object.

Blob object is binary data. For example, the object created by new Blob () is Blob object. For example, in XMLHttpRequest, if responseType is specified as blob, the return value is also an 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 will be released. After being released, the object URL will no longer point to the specified file.


downloadUrl && URL.revokeObjectURL(downloadUrl);

4. Vue. js upload and download files


<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 a file (POST)</el-button>
        <h3> File download: </h3>
        <el-button type="primary" @click="downloadLink"> Download Linked Files (window.open)</el-button>
        <el-button type="primary" @click="downloadBlobByGet">2 Binary stream download (GET)</el-button>
        <el-button type="primary" @click="downloadBlobByPost">2 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 a file 
            getFile(event) {
                this.file = event.target.files[0];
            },
 
            //  Upload a 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 succeeded !");
                }).catch(() => {
                    this.$message.error(" Please upload the file first !");
                })
            },
 
            //  Download Linked Files (window.open)
            downloadLink() {
                if (this.fileName) {
                    window.open("http://localhost:3000/download/test?fileName=" + this.fileName);
                }
            },
 
            // 2 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);
            },
 
            // 2 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 type of data returned by the return 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>

Related articles: