zoukankan      html  css  js  c++  java
  • ajax文件下载

    js

    function _es_preDownload(id, fileName) {
        $.ajax({
            url: '${ctx}/fdAttach/download',
            type: 'post',
            async: false,
            mimeType: 'text/plain; charset=x-user-defined',//jq ajax请求文件流的方式  (起作用的重点)
            data: {id: id},
            success: function (data) {
                var rawLength = data.length;
                var array = new Uint8Array(new ArrayBuffer(rawLength));
                for (i = 0; i < rawLength; i++) {
                    array[i] = data.charCodeAt(i) & 0xff;
                }
                //上面是把后台请求到的文件流进行转化为符合的流
                var blob = new Blob([array]);
                try {
                    var res = $.parseJSON(data);
                    if (res.code && res.code != Ajax.statusCode.ok) {
                        // 中文乱码问题
                        blob.text().then(function (res) {
                            res = $.parseJSON(res);
                            Dialog.error(res.message);
                            return;
                        });
                    }
                    return;
                }
                catch (e) {
                }
    
                Dialog.success("下载成功!");
    
                if ('download' in document.createElement('a')) {
                    //非IE下载
                    const elink = document.createElement('a');
                    elink.download = fileName;
                    elink.style.display = 'none';
                    elink.href = URL.createObjectURL(blob);
                    document.body.appendChild(elink);
                    elink.click();
                    URL.revokeObjectURL(elink.href);
                    document.body.removeChild(elink);
                }
                else {
                    navigator.msSaveBlob(blob, fileName);
                }
    
            }
        });
        return false;
    }
    

    java

    @RequestMapping("/download")
    public void download(String id, HttpServletResponse response)
        throws Exception {
        FileInfo fileInfo = fdAttachService.download(id);
        InputStream is = fileInfo.getInputStream();
        response.setContentType("application/force-download");
        IOUtils.copy(is, response.getOutputStream());
    }
    
  • 相关阅读:
    流畅的python,Fluent Python 第十章笔记
    foo
    std140
    android 开发注意事项
    Android ABI
    mac 基本
    build automation software 自动构建工具
    修改环境变量
    hyphenation
    Latency
  • 原文地址:https://www.cnblogs.com/zhuxiang1633/p/14713358.html
Copyright © 2011-2022 走看看