Jquery 下载RESTful服务返回的文件的Ajax调用
我对AJAX相当陌生。我正在使用AJAX向服务器发送请求。该服务返回一个文本文件。但返回数据时不显示下载框。 返回文件的rest服务如下所示:Jquery 下载RESTful服务返回的文件的Ajax调用,jquery,ajax,rest,Jquery,Ajax,Rest,我对AJAX相当陌生。我正在使用AJAX向服务器发送请求。该服务返回一个文本文件。但返回数据时不显示下载框。 返回文件的rest服务如下所示: @Path("/examples") public class ExampleCodesRest { @POST @Path("/getcode") @Produces(MediaType.TEXT_PLAIN) public Response getCodes(@Context ServletContext cont
@Path("/examples")
public class ExampleCodesRest {
@POST
@Path("/getcode")
@Produces(MediaType.TEXT_PLAIN)
public Response getCodes(@Context ServletContext context){
String in=context.getRealPath("/WEB-INF/reports.jrxml");
File file=new File(in);
ResponseBuilder response = Response.ok((Object) file);
response.header("Content-Disposition",
"attachment; filename=\"file_from_server.log\"");
return response.build();
}
}
$('a#link').click(function(event){
event.preventDefault();
$.ajax({
url: '/reports/rest/examples/getcode',
type: 'POST'
});
});
我的AJAX调用如下所示:
@Path("/examples")
public class ExampleCodesRest {
@POST
@Path("/getcode")
@Produces(MediaType.TEXT_PLAIN)
public Response getCodes(@Context ServletContext context){
String in=context.getRealPath("/WEB-INF/reports.jrxml");
File file=new File(in);
ResponseBuilder response = Response.ok((Object) file);
response.header("Content-Disposition",
"attachment; filename=\"file_from_server.log\"");
return response.build();
}
}
$('a#link').click(function(event){
event.preventDefault();
$.ajax({
url: '/reports/rest/examples/getcode',
type: 'POST'
});
});
该文件在没有AJAX的情况下下载成功。
使用AJAX时,它不会下载文件。请给出建议。建议很简单:您不能通过AJAX下载文件-这是一项安全策略。我的意思是,您可以下载数据,但不能从JavaScript端将其保存到磁盘
如果您想在单击时下载文件,则只需将
href
添加到标签中即可。或者用文件的URL
打开一个新窗口,建议很简单:不能通过AJAX下载文件-这是一种安全策略。我的意思是,您可以下载数据,但不能从JavaScript端将其保存到磁盘
如果您想在单击时下载文件,则只需将href
添加到标签中即可。或者使用文件的URL
a)打开一个新窗口,您没有回调来接收返回的数据
b) 将错误回调添加到代码中,以便查看调用后是否存在接收错误:
$.ajax({
url: '/spaconsole/rest/examples/getcode',
type: 'POST'
success: function (data) {
console.log('ok');
},
error: function (xhr) {
console.log(xhr);
}
});
编辑:如果要在页面中显示文本,则此选项可用。如果你想下载文件,这不是办法,你不能使用ajax。A)你没有回调来接收返回的数据
b) 将错误回调添加到代码中,以便查看调用后是否存在接收错误:
$.ajax({
url: '/spaconsole/rest/examples/getcode',
type: 'POST'
success: function (data) {
console.log('ok');
},
error: function (xhr) {
console.log(xhr);
}
});
编辑:如果要在页面中显示文本,则此选项可用。如果你想下载文件,这不是办法,你不能使用ajax,你不能直接从ajax下载,但是你可以通过一个iframe来启动下载。有关讨论,请参阅。您不能直接从AJAX执行此操作,但可以通过使用iframe启动下载来绕过此问题。有关讨论,请参阅。谢谢您的回复。我正在从服务器端获取数据,但没有将数据保存到磁盘的提示。谢谢您的回复。我正在从服务器端获取数据,但没有将数据保存到磁盘的提示。谢谢您的回复。经过一些研究,我似乎最多可以打开一个窗口来显示内容,但我无法将其保存到磁盘。谢谢您的回复。经过一些研究之后,我似乎最多只能打开一个窗口来显示内容,但我无法将其保存到磁盘