java下载文件工具类

java下载文件工具类

1.封装工具类

public class FileDownloadUtil {


    public static void fileDownload(String path, HttpServletResponse response) throws IOException {

        File file = new File(path);
        log.info(file.getPath());
        // 获取文件名
        String filename = file.getName();
        // 获取文件后缀名
        String ext = filename.substring(filename.lastIndexOf(".") + 1).toLowerCase();
        log.info("文件后缀名:" + ext);
        // 将文件写入输入流
        FileInputStream fileInputStream = new FileInputStream(file);
        InputStream fis = new BufferedInputStream(fileInputStream);
        byte[] buffer = new byte[fis.available()];
        fis.read(buffer);
        fis.close();
        // 设置response的Header
        response.setCharacterEncoding("UTF-8");
        // filename表示文件的默认名称,因为网络传输只支持URL编码的相关支付,因此需要将文件名URL编码后进行传输,前端收到后需要反编码才能获取到真正的名称
        response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
        // 告知浏览器文件的大小
        response.addHeader("Content-Length", "" + file.length());
        OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
        response.setContentType("application/octet-stream");
        outputStream.write(buffer);
        outputStream.flush();
    }

}

2.调用接口

 /**
     * 下载excel模板
     */
    @CrossOrigin
    @RequestMapping("/download")
    public void download(HttpServletResponse response) throws FileDownloadException {
        // 获取模板存储路径
        String path = this.getClass().getClassLoader().getResource("clothing-import.xlsx").getPath();
        try {
            FileDownloadUtil.fileDownload(path, response);
        } catch (IOException e) {
            log.error("模板下载失败!");
            throw new FileDownloadException(ErrorCode.EXCEL_DOWNLOAD_ERROR.getCode(), ErrorCode.EXCEL_DOWNLOAD_ERROR.getMsg());
        }
    }

3.前端调用

 methods: {
    filedownload (data) {
        if (!data) {
            return
        }
        let url = window.URL.createObjectURL(new Blob([data]))
        let link = document.createElement('a')
        link.style.display = 'none'
        link.href = url
        link.setAttribute('download', '衣物导入模板.xlsx')

        document.body.appendChild(link)
        link.click()
    },
    // 封装request请求,或者直接axiox调用后台接口
    download(){
      getDownload().then((res) => {
        this.filedownload(res)
      });
    },
    }
3.1 封装的request
// 下载模板

export function getDownload() {
  return request({
    url: '/clothes/download',
    method: 'get',
    responseType: 'blob',

  })
}
  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值