簡體   English   中英

Spring Rest和jQuery Ajax文件下載

[英]Spring Rest and jQuery Ajax File Download

我目前正在使用jQuery和Spring Rest。 jQuery用於將文件上載和下載到服務器。 上傳過程工作正常但我下載文件沒什么問題。 因此,在視圖中,用戶將選擇要下載的n個文件並單擊下載按鈕。 用戶單擊該按鈕后,將下載文件。 我不想為每個文件下載打開一個新的新選項卡。 我想在同一窗口下載而不刷新當前視圖。 我調查了這個,但對我幫助不大。 有什么辦法,我能做到嗎?

這是我下載文件的解決方案:

彈簧控制器方法:

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

幾分鍾前我回答了類似的問題: 從響應用戶發送文件,Spring REST + jQuery


我建議你使用這個JS插件https://github.com/johnculviner/jquery.fileDownload來直接使用$ .ajax下載文件。 你可以在那里找到所有官方文檔。

另外,在你的控制器中,你必須使用你的HttpServletResponse並在outputstream中寫入byte [],你必須在響應中放入一個cookie來建議JS插件(因為它需要它)

例如:

@RequestMapping(value = "/download", method = RequestMethod.GET)
    public void getFilesInZIP(@RequestParam("filenames[]") String[] filenames, HttpServletResponse httpServletResponse){
        byte[] file = service.packFilesToZIPArchiveAndReturnAsByteArray(filenames);

        Cookie cookie = new Cookie("fileDownload", "true");
        cookie.setPath("/");

        httpServletResponse.addCookie(cookie);
        httpServletResponse.setContentType("application/zip");
        httpServletResponse.setHeader("Content-Disposition", "attachment;filename=files.zip");
        httpServletResponse.getOutputStream().write(file);

    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM