我想实现从服务器下载(使用
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显示回应:
- 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. ***
如何处理和强制浏览器使用jQuery下载文件?
解决方法
通常使用两个选项,但不包括Ajax.而jQuery也不会是很大的帮助:
选项1:IFrame
在您的页面中放置无阻的IFrame:
- <iframe id="downloadFrame" style="display:none"></iframe>
当下载应该开始(你没有提到它是如何触发的),使用Javascript(和可能的jQuery)设置IFrame的URL,这在你的情况下是/ getInvoice / approvalId / 123:
- var iframe = document.getElementById("downloadFrame");
- iframe .src = "/getInvoice/approvalId/123";
设置IFrame URL应触发浏览器显示下载对话框.
选项2:导航到下载URL
第二个选项更简单.只需浏览下载网址即可.浏览器一旦知道它是一个无法显示的MIME类型,它将显示一个下载对话框.
所以当下载被触发时,执行以下Javascript代码:
- window.location.href = "/getInvoice/approvalId/123";
注意:
我不知道所有浏览器是否可靠地呈现带有PDF文件的下载对话框.某些浏览器可能会尝试在浏览器本身中显示它.内容处置标题是有帮助的,但不能保证.