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

TypeScript namespace explanation

Table of contents 1. Definition and Use 1.1 Defin...

Solution to Linux QT Kit missing and Version empty problem

Currently encountering such a problem My situatio...

Tomcat common exceptions and solution code examples

The company project was developed in Java and the...

MySQL 8.0.25 installation and configuration method graphic tutorial

The latest download and installation tutorial of ...

The whole process of configuring hive metadata to MySQL

In the hive installation directory, enter the con...

Docker container orchestration implementation process analysis

In actual development or production environments,...

Vue3 (III) Website Homepage Layout Development

Table of contents 1. Introduction 2. Actual Cases...

HTML blockquote tag usage and beautification

Blockquote Definition and Usage The <blockquot...

Docker builds cluster MongoDB implementation steps

Preface Due to the needs of the company's bus...

A brief discussion on the VUE uni-app development environment

Table of contents 1. Through HBuilderX visual int...

Three methods to modify the hostname of Centos7

Method 1: hostnamectl modification Step 1 Check t...

Explanation of nginx load balancing and reverse proxy

Table of contents Load Balancing Load balancing c...

Example of usage of keep-alive component in Vue

Problem description (what is keep-alive) keep-ali...

Page Speed ​​Optimization at a Glance

I believe that the Internet has become an increas...