Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
538 views
in Technique[技术] by (71.8m points)

jquery - Ajax call to download file returned from RESTful service

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();

    }
}

My AJAX call is as follows:

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...