Encountered in the development of this functionality, users to upload files or attachments to the server and the back-end put files on the FTP or other position, in the front page to download entrance, sometimes, the back-end returns the blob, this kind of situation, of course, is the best, but for convenience, the back-end may also return the url of the location in which the file, then, for the front, may For example, when downloading files, the browser may flash. When downloading images, JSON files and other files supported by the browser, the browser will not download them, but directly open these files in the browser. The following method can solve this problem perfectly

Solution:

  • Encapsulate custom directives
  • Change the URL to bold and download the blob under the create A TAB

Code implementation

  1. Create a new directory, downLoadUrl, under the directive folder under SRC

  1. DownLoadUrl/index.js file
/* * Back end returns the url of the file, front end creates a tag to download * * 1. [Fixed] Click download to open the file if the file is an image or browser supported format. * 2. The browser will flash when downloading files. * * Use * 1. Import downLoad from '@/directive/down-load-url' * 2. Directives :{downLoad} * 3. 
      
        downLoad 
       */

import downLoad from './downLoad'

const install = function(Vue) {
  Vue.directive('downLoadUrl', downLoad)
}

downLoad.install = install

export default downLoad
Copy the code
  1. DownLoadUrl/download. js file
export default {
    bind(el, binding) {
        if (binding.value.url) {
            el.addEventListener('click'.() = > {
                const a = document.createElement('a')
                // let url = baseUrl + binding.value // Let url = baseUrl + binding.value
                const url = binding.value.url // Full urls are used directly
                // Convert url to blob address,
                fetch(url).then(res= > res.blob()).then(blob= > { // Convert link address character content to bloB address
                    a.href = URL.createObjectURL(blob)
                    console.log(a.href)
                    a.download = binding.value.name || ' ' // Download the file name
                    / / a. d. ownload url = split ('/') [url. The split ('/'). The length of 1] / / / / download file name
                    document.body.appendChild(a)
                    a.click()
                })
            })
        }
    }
}
Copy the code
  1. inmain.jsRegister custom directives

use

Return an object{ url: '', name: ''}

Pay attention to

1. If the URL of the file is cross-domain, the download may fail. After the FETCH request is cross-domain, the resource cannot be obtained and subsequent operations cannot be performed.

2, you can also set the browser, for such as PDF, images and other resources do not directly open, directly download, and then simply create a label to download.

Original link: blog.csdn.net/weixin_4597…