JAVA Vue实现文件下载

后台controller

    @GetMapping("/DownloadWorkorderFile")
    @ResponseBody
    public void DownloadWorkorderFile(HttpServletRequest request, HttpServletResponse response, String filePath){
    
    
        File file = new File(filePath);
        // 取得文件名。
        String fileName = file.getName();
        InputStream fis = null;
        try {
    
    
            fis = new FileInputStream(file);
            request.setCharacterEncoding("UTF-8");
            String agent = request.getHeader("User-Agent").toUpperCase();
            if ((agent.indexOf("MSIE") > 0) || ((agent.indexOf("RV") != -1) && (agent.indexOf("FIREFOX") == -1)))
                fileName = URLEncoder.encode(fileName, "UTF-8");
            else {
    
    
                fileName = new String(fileName.getBytes("UTF-8"), "ISO8859-1");
            }
            response.reset();
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/force-download");// 设置强制下载不打开
            response.addHeader("Content-Disposition", "attachment;filename=" + fileName);
            response.setHeader("Content-Length", String.valueOf(file.length()));

            byte[] b = new byte[1024];
            int len;
            while ((len = fis.read(b)) != -1) {
    
    
                response.getOutputStream().write(b, 0, len);
            }
            response.flushBuffer();
            fis.close();
        }catch (IOException e) {
    
    
            throw new RuntimeException(e);
        }

    }

前端Vue

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

<script>

export default {
    
    
  data() {
    
    
    return {
    
    
    };
  },
  methods: {
    
    
    // 下载事件
    download() {
    
    
      var path = '/home/axs-spring/data/ceshi.png';
      window.open("http://localhost:8041/Management/DownloadWorkorderFile?filePath=" + encodeURI(path));
    },
  }
};
</script>

猜你喜欢

转载自blog.csdn.net/weixin_43851064/article/details/110234449