更新的问题: 在服务器端我有一个如下的服务,如果我想使用ajax在客户端触发调用,我应该怎么做?
在服务器中: Java/Spring
@GET
@Produces("application/vnd.ms-excel")
@Path("permissions/all/{userList}")
public Response allPermissionsExcel(@PathParam("userList") String userList) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
HSSFWorkbook wb;
try {
String[] groupList = userList.split(",");
wb = this.excelPermissionsService.getPermissionsExcelWorkbook(groupList);
wb.write(baos);
} catch (IOException e) {
e.printStackTrace();
} finally {
baos.close();
}
byte[] bytes = baos.toByteArray();
ResponseBuilder response = Response.ok(bytes);
response.header("Content-Disposition", "attachment; filename=export.xls");
return response.build();
}
在客户端:
$scope.exportToExcel = function() {
var promise = usersResource.getExcelPermissions($scope.userList);
promise.$promise.then(function(data) {
//I tried to convert to blob then save it with FileSaver.js, but I got an issue in converting the object to blob.
var blob = new Blob([data],
var blob = new Blob([data],
{type: "application/octet-stream"});
saveAs(blob, "exportThis.xls");
});
};
在客户端,如果我使用ajax(上面的代码)触发对服务器的调用,它返回一个对象,但没有任何提示下载,除非我使用
window.location = "url here";
触发调用。但这是一个重定向,并在所有 javascript 运行后弹出下载。
由于我有一些由 $watch 应用的加载动画,我需要使用 ajax 来触发调用,而不是使用 window.location。
谁能帮我在客户端保存“数据”对象excel? 谢谢!
最佳答案
您需要使用 window.open 而不请求 ajax 它只会打开一个新窗口,然后文件将开始下载,而不影响当前页面
window.open("permissions/all/1"); // instead of window.location because it will move you to another page
您也可以通过这样的弹出窗口打开它
newwindow=window.open("permissions/all/1","Window name",'height=50,width=150); // this one is better because it will open a small window without hiding the current window
if (window.focus) {newwindow.focus()}
return false;
关于java - 我应该如何使用 ajax 触发 Web 服务调用以导出 Excel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49155101/