jQuery_Ajax下載服務器文件流的方法

一般ajax,只能處理xml, json, script, or html類型,對返回的文件流卻沒辦法下載了。

本人編寫了一個AJAX插件,實現文件流下載。

然後JAva後臺採用往response裏寫文件流推送給前臺。

廢話不說,代碼完整奉上,拿走不謝!

01.jQuery_ajax_document.js

/**
 * Ajax下載服務器文件流的方法
 * @date 2020-01-20
 * @author quyunde
 */
;
(function($) {
    $.extend({
        ajaxDocument: function(option) {

            /**
             * option:配置項
             *  {
             *     url,地址
             *     type, 請求類型POST,GET

             *     header,請求頭token等設置
             *     param 參數
             *
             *  }
             */

            debugger;
            if(!option) {
                throw "param is error or NULL!";
            }
            if(!option.url) {
                throw "url is NULL or length=0!";
            }
            if(!option.type) {
                throw "type is NULL!";
            }

            const promise = new Promise(function(resolve, reject) {
                const handler = function() {
                    if(4 !== this.readyState) {
                        return false;
                    }
                    if(200 === this.status) {
                        resolve(this.response);
                    } else {
                        reject(new Error(this.statusText));
                    }
                };
                const client = new XMLHttpRequest();
                client.open(option.type, option.url, true);
                client.onreadystatechange = handler;
                client.responseType = "blob";

                if(option.header) {
                    for(key in option.header) {
                        client.setRequestHeader(key, option.header[key]);
                    }
                }
                client.send(option.param);

            });
            return promise;
        }

    });

})(jQuery);

 

02.loadWord.html

<!DOCTYPE html>
<html>

    <head>
        <meta charset="UTF-8">
        <title></title>
        <script src="/js/jquery-2.1.1.min.js" type="text/javascript" charset="utf-8"></script>
        <script src="/js/plugin/jQuery_ajax_document.js" type="text/javascript" charset="utf-8"></script>
    </head>

    <body>
        <div>
            <!-- 下載方法-->
            <input type="button" οnclick="download_word()" value="下載_word"></input>
        </div>
        <script>
            function download_word() {
                var option = {

                    url: '/wordTmplate/word',
                    type: 'GET',
                    param: {},
                    header: {
                        "token": localStorage.getItem("token")
                    }
                };
                $.ajaxDocument(option).then(function(data) {
                    debugger;
                    var blob = data;
                    // 獲取返回值
                    var a = document.createElement('a');
                    a.download = '下載文檔.docx';
                    a.href = window.URL.createObjectURL(blob);
                    a.click();
                }, function() {

                });

            }
        </script>
    </body>

</html>

 

03.java後端返回response 、OutputStream 流文件

 

package com.boot.security.server.wordTemplate.controller;

 

@Controller
@RequestMapping("/wordTmplate")
public class WordTempplateController {

    @RequestMapping(value = "/word", method = RequestMethod.GET)
    @ResponseBody
    public void getWord(String path, HttpServletRequest request, HttpServletResponse response) {
        try {
            String url = "D:\\abc.docx";
            File file = new File(url);
            String l = request.getRealPath("/") + "/" + url;
            String filename = file.getName();
            InputStream fis = new BufferedInputStream(new FileInputStream(file));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            response.reset();
            // 設置response的Header
            response.addHeader("Content-Length", "" + file.length());
            response.setContentType("application/x-msdownload;");

            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            toClient.write(buffer);
            toClient.flush();
            toClient.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    
    }
    
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章