使用Spring Service的AJAX GET下载文件 [英] Downloading a file using AJAX GET from Spring Service

查看:122
本文介绍了使用Spring Service的AJAX GET下载文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



这是我的AJAX调用:

  function downloadFile(fileName){
$ .ajax({
url:SERVICE_URI +files /+ fileName,
contentType:'application / json',
类型:'GET',
成功:函数(数据)
{
alert(done!);
} ,
error:function(error){
console.log(error);
}
});

$ / code $ / pre

这是我的Spring服务方法GET:

  @RequestMapping(value =/ files / {file_name},method = RequestMethod.GET)
public void getFile(@PathVariable(file_name )字符串fileName,
HttpServletResponse响应){
尝试{
//将您的文件作为InputStream
FileInputStream fis = new FileInputStream(fileName +.csv);
InputStream is = fis;
//将其复制到响应的OutputStream
ByteStreams.copy(is,response.getOutputStream());
response.setContentType(text / csv);
response.flushBuffer();
} catch(IOException ex){
throw new RuntimeException(IOError将文件写入输出流);
}

}

当我的客户端请求现有文件从服务器,AJAX success()方法被执行,但文件甚至没有下载。我做错了什么?

解决方案

不要使用ajax,只需将window.location.href设置为文件的url并在您的服务器脚本中设置http内容处置标题,强制浏览器保存文件。

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


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?

解决方案

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;
}

这篇关于使用Spring Service的AJAX GET下载文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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