【发布时间】:2017-04-13 15:24:27
【问题描述】:
我有一个向服务器发送发布请求的链接(“a”元素)。服务器响应一个我想在客户端下载的 excel 文件。
服务器代码:
@RequestMapping(value="/applicabilityExcel", method=POST)
@ResponseBody
public void getApplicability(@RequestParam("id") String reportId, HttpServletResponse response, HttpServletRequest request) throws IOException{
int id = Integer.valueOf(reportId);
Report report = repository.getReport(id);
InputStream is = new ExcelWriter().getConformityMatrix(report);
response.setContentType("application/vnd.ms-excel");
org.apache.commons.io.IOUtils.copy(is, response.getOutputStream());
response.flushBuffer();
}
客户代码:
<a class="appMatrix" href="<c:out value="${report.id}" />"> App</a>
$(".appMatrix").click(function(e) {
e.preventDefault();
$.post( "/applicabilityExcel",
{id:$(this).attr("href")},
function(data){
console.log(data);
//I have the file in data variable and I need now to stock it in the client machine (open dialog window, save it directly...)
});
});
我的问题是我不知道如何在客户端计算机中存储此文件(“下载它”)。
我尝试将文件下载为 text/base64,将其放在“a”元素的 href 上并调用 click(),但它对我不起作用。
欢迎所有回复和建议。
【问题讨论】:
-
最简单的方法是将表单发布到相同的 url ...然后会自动强制下载
-
jQuery 在
$.ajax()处理二进制数据时出现问题。data在$.post()成功回调中是什么? -
@guest271314
data是服务器响应 (org.apache.commons.io.IOUtils.copy(is, response.getOutputStream());)。它包含一个excel文件的输入流 -
您是否尝试过使用
XMLHttpRequest()并将.responseType设置为"blob",或fetch(),Response.blob()? -
@charlietfl,使用表单可以正常工作,但文件名设置为默认文件名。您知道如何设置文件名吗? JavaScript 代码是:
$('<input name="id" />').attr('type', 'hidden') .attr('value',$(this).attr("href")) .appendTo('#formD'); $('#formD').submit();
标签: javascript java jquery html spring-mvc