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
369 views
in Technique[技术] by (71.8m points)

java - Downloading a file using AJAX GET from Spring Service

I'm trying to implement a Service that automatically starts a download with the requested file.

This is my AJAX call:

function downloadFile(fileName) {
  $.ajax({
    url : SERVICE_URI + "files/" + fileName,
    contentType : 'application/json',
    type : 'GET',
    success : function (data)
    {
      alert("done!");
    },
    error: function (error) {
      console.log(error);
    }
  });
}

and this is my Spring Service method GET:

@RequestMapping(value = "/files/{file_name}", method = RequestMethod.GET)
public void getFile(@PathVariable("file_name") String fileName,
                    HttpServletResponse response) {
    try {
        // get your file as InputStream
        FileInputStream fis = new FileInputStream( fileName + ".csv" );
        InputStream is = fis;
        // copy it to response's OutputStream
        ByteStreams.copy(is, response.getOutputStream());
        response.setContentType("text/csv");
        response.flushBuffer();
    } catch (IOException ex) {
        throw new RuntimeException("IOError writing file to output stream");
    }

}

When my client requests the existing file from the server, the AJAX success() method is executed but the file is not even downloading. Am I doing anything wrong?

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

Don't use ajax, just set window.location.href to the url of the file and set the http content disposition header in your server script to force the browser to save the file.

function downloadFile(fileName) {
  window.location.href = SERVICE_URI + "files/" + fileName;
}

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

...