浏览器下载文件

时间:2022-06-25 16:46:50

前言

ajax请求无法下载文件,因为ajax回调的response会直接把返回的二级制流当成字符串处理,不会写到文件中。

前端代码

由于不能使用ajax异步下载,那么想要在不刷新页面条件下下载文件,我们可以使用虚拟表单提交。

虚拟表单

/**
 * @param verb 'POST' or 'GET'
 * @param urls 资源文件地址
 * @param datas 向后台传递的json参数
 * @param target '_blank' or '_self' 是否在空白页面打开
 */
function openNewPost(verb, urls, datas, target) {
    var form = document.createElement("form");
    form.action = urls;
    form.method = verb;
    form.target = target || "_self";
    if (datas) {
        for ( var key in datas) {
            var input = document.createElement("textarea");
            input.name = key;
            input.value = typeof datas[key] === "object" ? JSON
                    .stringify(datas[key]) : datas[key];
            form.appendChild(input);
        }
    }
    form.style.display = 'none';
    document.body.appendChild(form);
    form.submit();
    document.body.removeChild(form);
}

java代码

@RequestMapping(value ="downloadQrcode", method = RequestMethod.POST)
    public void downloadQrcode(HttpServletRequest request,HttpServletResponse response,String fileUrl) {
        try {
            if(StringUtil.isNullOrEmpty(fileUrl) || fileUrl.contains("notExistImg.jpg")){
            }
            service.downloadQrcode(response,fileUrl);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw new BusinessException("图片下载异常!");
        }
    }
public void downloadQrcode(HttpServletResponse response, String fileUrl)
            throws Exception {
        String fileName = "qrcode_" + DateUtil.getNowDateminStr() + ".jpg";
        BufferedInputStream bis = null;
        OutputStream out = null;
        // 建立链接
        URL url = new URL(fileUrl);
        HttpURLConnection httpUrl = (HttpURLConnection) url.openConnection();
        // 连接指定的资源
        httpUrl.connect();
        // 获取网络输入流
        bis = new BufferedInputStream(httpUrl.getInputStream());
        response.reset();
        //返回二进制流
        response.setContentType("application/octet-stream");
        //告诉浏览器是下载而不是打开该文件
        response.setHeader("Content-Disposition", "attachment; filename="
                + fileName);
        out = response.getOutputStream();
        byte[] buf = new byte[1024];
        int len = 0;
        while ((len = bis.read(buf)) > 0) {
            out.write(buf, 0, len);
        }
        out.flush();
        if (null != bis) {
            bis.close();
        }
        if (null != out) {
            out.close();
        }
    }