javascript - Spring Rest 和 jQuery Ajax 文件下载

标签 javascript jquery ajax spring spring-mvc

我目前正在使用 jQuery 和 Spring Rest。 jQuery 用于将文件上传和下载到服务器。上传过程工作正常,但我在下载文件时没有遇到什么问题。所以场景是,在 View 中,用户将选择要下载的 n 个文件并单击下载按钮。用户单击该按钮后,将下载文件。我不想为每个文件下载打开一个新的新选项卡。我想在不刷新当前 View 的情况下在同一个窗口上下载。我调查了this但对我帮助不大。有什么办法可以实现吗?

最佳答案

这是我下载文件的解决方案:

Spring Controller 方法:

@RequestMapping(value = "/download", method = RequestMethod.GET)
public void retrieveDocument(@RequestParam("id") String id, HttpServletResponse response) throws IOException {
    InputStream in = fileService.getFileStream(); // My service to get the stream.
    response.setContentType(MediaType.APPLICATION_OCTET_STREAM);
    response.setHeader("Content-Transfer-Encoding", "binary");
    response.setHeader("Content-Disposition", "attachment; filename=" + filename);
    try {
        IOUtils.copy(inputStream, response.getOuputStream()); //Apache commons IO.
        inputStream.close();
        response.flushBuffer();
        response.setStatus(HttpServletResponse.SC_OK);
    } catch (Exception e) {
        //log error.
    }

客户端函数:

function download(id) {
    var id = $('#file').attr('id')
    var xhr = new XMLHttpRequest();
    xhr.open('GET', 'url here' + id, true);
    xhr.responseType = 'arraybuffer';
    xhr.onload = function() {
        if(this.status == '200') {
           var filename = '';
           //get the filename from the header.
           var disposition = xhr.getResponseHeader('Content-Disposition');
           if (disposition && disposition.indexOf('attachment') !== -1) {
               var filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
               var matches = filenameRegex.exec(disposition);
               if (matches !== null && matches[1])
                   filename = matches[1].replace(/['"]/g, '');
           }
           var type = xhr.getResponseHeader('Content-Type');
           var blob = new Blob([this.response],  {type: type});
           //workaround for IE
           if(typeof window.navigator.msSaveBlob != 'undefined') {
               window.navigator.msSaveBlob(blob, filename);
           }
           else {
               var URL = window.URL || window.webkitURL;
               var download_URL = URL.createObjectURL(blob);
               if(filename) {
                   var a_link = document.createElement('a');
                   if(typeof a_link.download == 'undefined') {
                       window.location = download_URL;
                   }else {
                       a_link.href = download_URL;
                       a_link.download = filename;
                       document.body.appendChild(a_link);
                       a_link.click();
                   }
               }else {
                   window.location = download_URL;
               }
               setTimeout(function() {
                   URL.revokeObjectURL(download_URL);
               }, 10000);
           }
        }else {
            alert('error')';//do something...
        }
    }; 
    xhr.setRequestHeader('Content-type', 'application/*');
    xhr.send();
}

关于javascript - Spring Rest 和 jQuery Ajax 文件下载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32995666/

相关文章:

javascript - 无法通过 onClick 事件处理程序访问按钮 ID

javascript - 创建div后的Jquery点击事件

jquery - 页面加载后进行 Ajax 调用

jquery - 带有 bootstrap 垂直嵌套选项卡的 angularjs 使用 ajax 加载内容

javascript - 1000 个 div 上的 jQuery 单击事件,优化方法?

javascript - Django 和 JavaScript fetch() : CORS policy: No 'Access-Control-Allow-Origin' header is present

php - Html 自动刷新表格

javascript - 向 Javascript 数组添加空值

javascript - JQuery 进度条动画

javascript - 从 Delta on Quill 获取 HTML