preface

Recently, when I was working on a project, I often encountered the need to download files, and when I used AJAX to request to download files, I would encounter the problem that file streams were difficult to deal with. Therefore, this paper mainly provides methods of downloading files with A tag and IFrame tag

A tag downloads files

// 1. Assemble the requested address processing. In actual development, different addresses should be configured according to different environments
getUrl(id){
    return ` 127.0.0.1:8080? id=${id}`
}

// 2. Create a label using js, configure the attributes of the label, and click Download
downLoad(id){
    const url = this.getUrl(id)             / / get the url
    const a = document.createElement('a')   // Generate a tag
    a.href = url                            // Configure the address
    a.target = '_blank'                     // Open the download page in a new TAB
    a.click()                               // Click the A TAB
}

// 3. Call the downLoad method where necessary to open a new page in the browser and downLoad the file
downLoad(id)

// 4. If the file can be downloaded normally, the newly opened TAB page is closed. If the download fails, the TAB page is not closed
// This rule can be used to determine whether files can be downloaded normally
Copy the code

Iframe tag downloads files

A TAB will pop up a new window when downloading a file. If the project has high requirements for interaction, new pages are not allowed to pop up and files need to be downloaded, you can use the embedded IFrame page to download the file

// 1. Insert the iframe tag on the page and hide it. The initial URL value is empty
<iframe :src="url" style="display:none" />

// 2. Same as the first step of the a tag, get the URL
getUrl(id){
    return ` 127.0.0.1:8080? id=${id}`
}

// 3. Assign the url value to iframe
setIframeUrl(id){
    // The url is reset to empty so that files at the same address can be downloaded repeatedly
    this.url = ' '
    this.$nextTick(function() {
        this.url = this.getUrl(id)
    })
}

// 4. Call the setIframeUrl method where necessary
setIframeUrl(id)

// If the file fails to download, the page does not respond
Copy the code