Javascript 在客户端计算机上保存从服务器收到的excel文件
我有一个向服务器发送post请求的链接(“a”元素)。服务器用我想在客户端下载的excel文件进行响应 服务器代码:Javascript 在客户端计算机上保存从服务器收到的excel文件,javascript,java,jquery,html,spring-mvc,Javascript,Java,Jquery,Html,Spring Mvc,我有一个向服务器发送post请求的链接(“a”元素)。服务器用我想在客户端下载的excel文件进行响应 服务器代码: @RequestMapping(value="/applicabilityExcel", method=POST) @ResponseBody public void getApplicability(@RequestParam("id") String reportId, HttpServletResponse response, HttpServletRequest requ
@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...)
});
});
$(“.appMatrix”)。单击(函数(e){
e、 预防默认值();
$.post(“/applicatabilityExcel”,
{id:$(this.attr(“href”)},
功能(数据){
控制台日志(数据);
//我有数据变量中的文件,现在我需要将其存储在客户机中(打开对话框窗口,直接保存…)
});
});
我的问题是,我不知道如何将该文件存储在客户机(“下载”)中
我试图以text/base64的形式加载该文件,将其放在“a”元素的href上并调用click(),但它对我不起作用
欢迎所有回应和建议 也许你可以试试这个,对我有用
$scope.exportExcel = function(){
var self = this;
var url = //yourapi;
$http.get(url, { responseType: "arraybuffer" }).then(
function (result) {
var blob = new Blob([result.data], { type: 'application/vnd.ms-excel' });
var a = document.createElement('a');
var url = URL.createObjectURL(blob);
a.href = url;
a.download = ""//yourfilename
a.target = '_blank';
document.body.appendChild(a);
a.click();;
});
};
最简单的方法是将表单发布到同一个url…然后强制自动下载jQuery在处理二进制数据时出现问题。
$.ajax()
。$.post()
成功回调中的数据是什么?@guest271314数据是服务器响应(org.apache.commons.io.IOUtils.copy(is,response.getOutputStream());
)。它包含excel文件的输入流您是否尝试过使用XMLHttpRequest()
和.responseType
设置为“blob”
,或fetch()
,Response.blob()
?@charlietfl,使用的表单可以工作,但文件名设置为默认文件名。您知道如何设置文件名吗?javaScript代码是:$('').attr('type','hidden').attr('value',$(this.attr('href')).appendTo('#formD')$(#formD')。提交()
请注意,下载
在一些传统浏览器中不受支持谢谢您的回答,但我发现使用@charlietfl comment中建议的表单post是他提到的最简单的方法。