jQuery.get 与 window.open 区别

jQuery.get vs window.open difference

我正在尝试在我的 JSP servlet 应用程序中下载文件。 据我所知 jQuery.get() 和 window.open() 都发送获取请求。 我可以使用 window.open(CSVURL) 轻松下载文件,但是如果我尝试使用 jQuery.get() 进行同样的操作,它不会下载。 "doGet() function" 在 servlet 中运行但未下载任何内容,控制台日志中也没有错误。

此代码下载文件

  $("#exportcsv").click(function() {
            window.open(SomeURL);
        });

这不

 $("#exportcsv").click(function() {
            jQuery.get(CSVURL,Data).done(function() {});
        });

这是我的 Java 在 servlet

上的下载代码
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        downloadFile(somepath, req, resp);
    }


protected void downloadFile(String path, HttpServletRequest req, HttpServletResponse resp) {
        File file = null;
        InputStream in = null;
        ServletOutputStream outstream = null;
        try {
            String fileName = "csv";
            resp.reset();
            file = new File(path);
            in = new FileInputStream(file);
            resp.setContentType("text/csv");
            resp.addHeader("content-disposition", "attachment; filename=" + fileName);
            outstream = resp.getOutputStream();
            IOUtils.copyLarge(in, outstream);

        } catch (Exception e) {
            log.warn(e.getMessage());
        } finally {

            IOUtils.closeQuietly(outstream);
            IOUtils.closeQuietly(in);
            if (file != null)
                file.delete();
        }
    }

As far as i know jQuery.get() and window.open() both send get requests.

是的,但有两个显着差异:

  1. jQuery.get使用ajax,这是服从Same Origin Policy. window.open does not, and is not. So if the request is for a URL in another origin (different host, different port, and/or different protocol), jQuery.get will fail at the browser end (by default; CORS可以在服务器上使用允许它),但window.open会不是。

  2. 我认为 jQuery.get 不会触发浏览器对 Content-Disposition: attachment; ... header.

  3. 的默认处理

Problem might be caused by header. Could you suggest any workaround to download file without opening new tab?

我通常触发文件下载的方式是 post 一个表单(因为我通常需要 POST 为此)到一个隐藏的 iframe。在 Chrome 和 Firefox 上它不会打开任何 windows;在 IE 上,它确实存在,但只是在“另存为”对话框出现之前短暂出现。

对于 GET 请求,我相信你可以动态添加一个带有 hrefdownload attributea 元素,然后人为地点击它:

var a = $("<a download></a>")
        .attr("href", theURL)
        .css("display", "none")
        .appendTo(document.body)
        .click();
setTimeout(function() {
    a.remove();
    a = undefined;
}, 500);

...或者类似的东西。它必须在 Firefox 处理它的文档中。其他浏览器似乎很高兴,即使它不在文档中。