SpringBoot+Vue+Element-ui实现文件下载

目录

1.后端代码部分

2.前端代码部分

3.效果展示

1.后端代码部分

 @GetMapping("downloadFile")
    public void downloadFile(@RequestParam("filename") String filename,HttpServletResponse response) throws Exception {
        // 告知浏览器这是一个字节流,浏览器处理字节流的默认方式就是下载
        // 意思是未知的应用程序文件,浏览器一般不会自动执行或询问执行。浏览器会像对待,
        // 设置了HTTP头Content-Disposition值为attachment的文件一样来对待这类文件,即浏览器会触发下载行为
        response.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_OCTET_STREAM_VALUE);
        // ,该响应头指示回复的内容该以何种形式展示,是以内联的形式(即网页或者网页的一部分),还是以附件的形式下载并保存到本地。
        response.setHeader(HttpHeaders.CONTENT_DISPOSITION,"attachment;fileName="+ URLEncoder.encode(filename, "UTF-8"));
        File file = new File("d:/OBS/" + filename);
        //这里的“d:/OBS”是根据我路径下设置的,根据自己路径进行设置(注意要有相应的文件,方便下载)
        ServletOutputStream ros = response.getOutputStream();

        FileInputStream fis = new FileInputStream(file);
        byte[] bytes = new byte[2 * 1024];
        int len = 0;
        while ((len = fis.read(bytes)) != -1) {
            ros.write(bytes, 0, len);
        }

        ros.flush();
        ros.close();
        fis.close();

    }

2.前端代码部分

注意这里为了方便,省去了用axios作请求,而用href直接跳转,相当于一次请求访问

<template>
    <div>
      <el-button type="success" @click="downloadFile">下载文件</el-button>
    </div>
</template>

<script>
export default {

  methods: {
    downloadFile() {
      let a = document.createElement('a')
      a.href = 'http://127.0.0.1:8081/file/downloadFile?filename=pic.jpg'
    //上面根据自己配置情况作拼接
      document.body.appendChild(a)
      a.style.display = 'none'
      a.click()
      document.body.removeChild(a)
    }


  }
};
</script>

3.效果展示

 

 下载成功

猜你喜欢

转载自blog.csdn.net/Kristabo/article/details/131538115