如何使用 jQuery AJAX 和 Spring MVC 3 从服务器下载文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6722716/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 21:17:36  来源:igfitidea点击:

How to download file from server using jQuery AJAX and Spring MVC 3

jqueryspring-mvcdownload

提问by Tural

I want to implement downloading (with AJAX) of uploaded file from server. On the server side I wrote the code

我想实现从服务器下载(使用 AJAX)上传的文件。在服务器端我写了代码

@RequestMapping(value = "/getInvoice/approvalId/{approvalId}", method = RequestMethod.GET)
public
@ResponseBody
byte[] getInvoice(@PathVariable("approvalId") Integer approvalId, HttpServletResponse response) throws IOException {
    String fileName = this.approvalService.getFullInvoicePath(approvalId);
    File file = new File(fileName);

    response.setContentType("application/octet-stream");
    response.setHeader("Content-Disposition", "attachment; filename=\"" + file.getName() + "\"");
    response.setHeader("Pragma", "no-cache");
    response.setHeader("Cache-Control", "no-cache");
    response.setContentLength((int) file.length());
    return FileUtils.readFileToByteArray(file);
}

Fiddler2 shows response:

Fiddler2 显示响应:

HTTP/1.1 200 OK
Server: Apache-Coyote/1.1
Content-Disposition: attachment; filename="invoice.pdf"
Pragma: no-cache
Cache-Control: no-cache
Content-Type: application/octet-stream;charset=UTF-8
Content-Length: 1028351
Date: Sun, 17 Jul 2011 08:16:41 GMT

%PDF-1.4
%????
6 0 obj <</Linearized 1/L 1028351/O 8/E 1024254/N 1/T 1028185/H [ 5056 544]>>
endobj

xref
6 238 
*** FIDDLER: RawDisplay truncated at 128 characters. Right-click to disable truncation. ***

How to handle and force browser to download file using jQuery?

如何处理和强制浏览器使用 jQuery 下载文件?

回答by Codo

Two options are usually used but neither involves AJAX. And jQuery won't be a great help either.

通常使用两个选项,但都不涉及 AJAX。jQuery 也不会有很大帮助。

Option 1: IFrame

选项 1:IFrame

Place an invisibleIFrame into your page:

将一个不可见的IFrame 放入您的页面:

<iframe id="downloadFrame" style="display:none"></iframe>

When the download should start (you didn't mention how it is triggered), use Javascript (and possibly jQuery) to set the URL for the IFrame, which is something like /getInvoice/approvalId/123in your case:

当下载应该开始时(你没有提到它是如何触发的),使用 Javascript(可能还有 jQuery)来设置 IFrame 的 URL,这就像/getInvoice/approvalId/123你的情况:

var iframe = document.getElementById("downloadFrame");
iframe .src = "/getInvoice/approvalId/123";

Setting the IFrame URL should trigger the browser to present the download dialog.

设置 IFrame URL 应该会触发浏览器显示下载对话框。

Option 2: Navigate to the download URL

选项 2:导航到下载 URL

The second option is even simpler. Just navigate to the download URL. Once the browser figures out it's a MIME type that cannot be displayed, it will present a download dialog.

第二种选择更简单。只需导航到下载 URL。一旦浏览器确定它是无法显示的 MIME 类型,它就会显示一个下载对话框。

So when the download is triggered, execute the following JavaScript code:

因此,当触发下载时,执行以下 JavaScript 代码:

window.location.href = "/getInvoice/approvalId/123";


Note

笔记

I'm not sure if all browser will reliably present a download dialog with PDF files. Some browsers mighttry to display it within the browser itself. The Content-DispositionHTTP header is helpful but no guarantee.

我不确定所有浏览器是否都能可靠地显示包含 PDF 文件的下载对话框。某些浏览器可能会尝试在浏览器本身中显示它。在Content-DispositionHTTP标头是有益的,但不能保证。

回答by nidalpres

jQuery-ized answer by Codo:

Codo 的jQuery 化答案:

   $('#downloadFrame').remove(); // This shouldn't fail if frame doesn't exist
   $('body').append('<iframe id="downloadFrame" style="display:none"></iframe>');
   $('#downloadFrame').attr('src','/downloadUrlGoesHere');

回答by Peter Gutowski

Maybe a better strategy would be to use jQuery to build a new <A> link on the page that'll reference this same URL, and insert this new element at a appropriate place in the DOM. That being done, maybe jQuery can even then click it for the user, initiating the download.

也许更好的策略是使用 jQuery 在页面上构建一个新的 <A> 链接,该链接将引用相同的 URL,并将这个新元素插入 DOM 中的适当位置。完成后,也许 jQuery 甚至可以为用户单击它,启动下载。