我有一个链接(“a”元素),它向服务器发送一个post请求。服务器使用我想在客户端下载的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(),但它对我不起作用。
欢迎所有回复和建议。
答案 0 :(得分:0)
也许你可以在这里试试,对我有用
$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();;
});
};