我对 AJAX 还很陌生。我正在使用 AJAX 向服务器发送请求。该服务返回一个文本文件。但返回数据时没有出现下载框。 返回文件的rest服务如下:
@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();
}
}
我的AJAX调用如下:
$('a#link').click(function(event){
event.preventDefault();
$.ajax({
url: '/reports/rest/examples/getcode',
type: 'POST'
});
});
文件在没有 AJAX 的情况下下载成功。 使用 AJAX,它不会下载文件。请提出建议。
最佳答案
建议很简单:您不能通过 AJAX 下载文件 - 这是一项安全策略。我的意思是您可以下载数据,但无法从 JavaScript 端将其保存到磁盘。
如果您想通过点击下载文件,那么您只需将 href
添加到您的 a
标记即可。或者使用文件的 URL
打开一个新窗口。
关于jquery - Ajax 调用下载从 RESTful 服务返回的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12955266/