Ajax 调用以下载从 RESTful 服务返回的文件 [英] Ajax call to download file returned from RESTful service

查看:25
本文介绍了Ajax 调用以下载从 RESTful 服务返回的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 AJAX 还很陌生.我正在使用 AJAX 向服务器发送请求.该服务返回一个文本文件.但是返回数据时没有出现下载框.返回文件的rest服务如下:

I am fairly new to AJAX. I am sending a request to server using AJAX. The service returns a text file. But no download box appears when data is returned. The rest service that returns the file is as follows:

@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 调用如下:

My AJAX call is as follows:

 $('a#link').click(function(event){
    event.preventDefault();
    $.ajax({
        url: '/reports/rest/examples/getcode',
        type: 'POST'
    });
}); 

文件下载成功,没有 AJAX.使用 AJAX,它不会下载文件.请指教.

The file downloads successful without AJAX. With AJAX, it doesn't download the file.Please advice.

推荐答案

建议很简单:您不能通过 AJAX 下载文件 - 这是一项安全策略.我的意思是您可以下载数据,但不能从 JavaScript 端将其保存到磁盘.

Advice is simple: you cannot download files via AJAX - it's a security policy. I mean you can download the data, but you can't save it to disk from JavaScript side.

如果您想通过点击下载文件,那么您只需将 href 添加到您的 a 标签即可.或者打开一个包含文件 URL 的新窗口.

If you want to download a file on click, then you can just add href to you a tag. Or open a new window with file's URL.

这篇关于Ajax 调用以下载从 RESTful 服务返回的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆