栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Spring Rest和jQuery Ajax文件下载

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Spring Rest和jQuery Ajax文件下载

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

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


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/382360.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号