Realize static file download in Vue (take download form as an example)

Application scenario : Sometimes we need to download a small number of files and the content is fixed and static files (such as templates, etc.), then the download function can be completed on the front end without interacting with the server. To download content is more complex dynamic file, please move Portal: Vue achieve file stream downloads

Vue-cli version of this article: 3.x, 4.x

1. Place the files to be downloaded in the
public folder . Files in the public folder will not be processed by Webpack, they will be copied directly to the final packaging directory. These files
must be referenced using absolute paths . Simply put, public is used to store files that have not changed for thousands of years.
Insert picture description here
2. Code implementation in the component

<template>
  <div class="about">
    <el-button type="primary" @click="download">下载</el-button>
  </div>
</template>

<script>
export default {
    
    
  data() {
    
    
    return {
    
    };
  },
  methods: {
    
    
    download(){
    
    
      let a = document.createElement('a');
      a.href = `/static/test.xlsx`;
      a.download = '测试表格.xlsx';
      a.click();
    }
  },
  mounted() {
    
    },
};
</script>

3. dist file
Insert picture description here
Finally, the dist package can be deployed on the server

Guess you like

Origin blog.csdn.net/ZYS10000/article/details/112035431