How does Vue download non-same-origin files based on URL

How does Vue download non-same-origin files based on URL

Generally speaking, we can have the following two solutions when downloading files based on URL:

1. window.open(url)
2. <a :href="url" rel="external nofollow" download="file name"/>

However, during the development process, we sometimes encounter situations where the file address returned by the backend is not from the same source as our website. When using the above two solutions to download images, PDFs and other files, the browser will open them directly instead of downloading them. The following method can solve this situation:
Download file function encapsulation: (views/util/index.js)

import axios from "axios";
// Download the file (can solve the cross-domain download problem)
export async function downloadFile(fileUrl, fileName) {
  if (!fileUrl) return;
  let res = await axios({
    method: "get",
    url: fileUrl,
    responseType: "blob"
  });
  let newUrl = window.URL.createObjectURL(res.data);
  let a = document.createElement("a");
  a.href = newUrl;
  a.download = fileName;
  a.click();
  a.remove();
  //After the resource download is complete, you can manually clear the cache resources occupied by createObjectURL window.URL.revokeObjectURL(newUrl);
}

use

<template>
  <div>
      {{file.name}}
      <span
        class="file-download"
        @click="downloadFile(file.url, file.name)"
        >Download
      >
  </div>
</template>

<script>
import { downloadFile } from "@/util/index.js";
export default {
  components: {},
  data() {
    return {
      file:{
          url:'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fb.zol-img.com.cn%2Fdesk%2Fbizhi%2Fimage%2F6%2F960x600%2F1426818724752.jpg&refer=http%3A%2F%2Fb.zol-img.com.cn&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1627377638&t=662034e86ff9110854ca0316485e294b',
          name:'Beautiful scenery'
      }
    };
  },
  created() {},
  mounted() {},
  methods: {
    downloadFile
  }
};
</script>

<style lang="scss" scoped>

</style>

PS: The best solution for downloading files by clicking URL in vue

This kind of function is often encountered in development. Users upload files or attachments to the server, and the backend puts the files in FTP or other locations. There is a download entry in the front-end page. Sometimes, the backend returns a blob, which is of course the best. However, for convenience, the backend may also return the URL of the file location. At this time, the front-end may encounter some problems. For example, the browser may flash when downloading files. When downloading pictures, JSON files and other files supported by the browser, they will not be downloaded, but directly opened in the browser. The following method can perfectly solve such problems.

Solution:

  • Encapsulating custom instructions
  • Convert the URL to bold and create a tag to download the blob

Code Implementation

  • Create a new directory download-load-url in the directive folder under src
  • down-load-url/index.js file
/*
 * The backend returns the URL of the file, and the frontend creates a tag to download it*
 * 1. Solved the problem that if the file is a picture or a format supported by the browser, the file will be opened directly when clicking download.
 * 2. When downloading files, the browser may flicker*
 * Use in the page * 1. Import the directive import downLoad from '@/directive/down-load-url'
 * 2. Register directives:{downLoad}
 * 3. Use it as a command on the download button, for example: <el-button v-downLoad="url">Download</el-button>
 */

import downLoad from './downLoad'

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

downLoad.install = install

export default downLoad
down-load-url/downLoad.js file export default {
  bind(el, binding) {
    el.addEventListener('click', () => {
      console.log(binding.value) // url
      const a = document.createElement('a')
      // let url = baseUrl + binding.value // If the url is incomplete, you need to concatenate baseURL
      const url = binding.value // The complete url is used directly // Here is to convert the url into a blob address,
      fetch(url).then(res => res.blob()).then(blob => { // Convert the link address string content into a blob address a.href = URL.createObjectURL(blob)
        console.log(a.href)
        a.download = '' // Name of the downloaded file// a.download = url.split('/')[url.split('/').length -1] // // Name of the downloaded filedocument.body.appendChild(a)
        a.click()
      })
    })
  }
}

This is the end of this article about how Vue can download non-same-origin files according to URL. For more relevant Vue URL download file content, please search 123WORDPRESS.COM's previous articles or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • vue.js downloads pictures according to picture url
  • Share the best solution for clicking URL to download files in Vue

<<:  Tutorial on installing rabbitmq using yum on centos8

>>:  Detailed explanation of how MySQL (InnoDB) handles deadlocks

Recommend

JS implements a simple counter

Use HTML CSS and JavaScript to implement a simple...

How to connect XShell and network configuration in CentOS7

1. Linux network configuration Before configuring...

Writing a web calculator using javascript

This article mainly records the effect of using j...

Analyze several common solutions to MySQL exceptions

Table of contents Preface 1. The database name or...

Summary of common MySQL commands

Set change mysqlroot password Enter the MySQL dat...

Tutorial on installing mysql5.7.17 via yum on redhat7

The RHEL/CentOS series of Linux operating systems...

Some suggestions for Linux system optimization (kernel optimization)

Disable swap If the server is running a database ...

A brief discussion on VUE uni-app template syntax

1.v-bind (abbreviation:) To use data variables de...

Detailed steps to install xml extension in php under linux

Installing XML extension in PHP Linux 1. Enter th...

How to build a deep learning environment running Python in Docker container

Check virtualization in Task Manager, if it is en...

jQuery implements dynamic tag event

This article shares the specific code of jQuery t...

How to insert video into HTML and make it compatible with all browsers

There are two most commonly used methods to insert...

mysql add, delete, modify and query basic statements

grammar Here is the generic SQL syntax for INSERT...

Practical method of deleting files from Linux command line

rm Command The rm command is a command that most ...