中打开

可以通过以下步骤实现:

  1. 后端接口返回文件流,可以使用类似于以下的代码:
@RequestMapping(value = "/download", method = RequestMethod.GET)
public void download(HttpServletResponse response) {
    try {
        InputStream inputStream = new FileInputStream(file);
        IOUtils.copy(inputStream, response.getOutputStream());
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
        response.flushBuffer();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

其中,file是要下载的文件,fileName是文件名。

  1. 前端通过ajax请求接口,获取文件流,可以使用以下代码:
function download() {
    $.ajax({
        url: "/download",
        type: "get",
        dataType: "blob",
        success: function (data) {
            var url = window.URL.createObjectURL(data);
            var a = document.createElement("a");
            a.href = url;
            a.download = "file.xlsx";
            a.click();
        }
    });
}

其中,blob表示返回的数据类型是二进制流,window.URL.createObjectURL(data)将二进制流转换为文件URL,然后创建一个虚拟的a标签,将URL赋给它的href属性,设置下载的文件名,并触发点击事件,即可在浏览器中打开或下载文件。


原文地址: https://www.cveoy.top/t/topic/7Gd 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录