用ajax下載字節流形式的excel文件

緣由:ajax請求只是個「字符型」的請求,即請求的內容是以文本類型存放的。文件的下載是以二進制形式進行的,ajax無法解析後臺返回的文件流,因此沒法處理二進制流response輸出來下載文件。前端

解決方法:使用form表單提交實現文件下載ajax

1,後臺代碼實現方法:json

// 生成excel文件
    @RequestMapping(value = "/study", method = RequestMethod.POST)
    public void study(@RequestBody ParamVO paramVO, HttpServletResponse response) throws UnsupportedEncodingException {
        response.setContentType("application/octet-stream;charset=utf-8");
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-disposition", "attachment;filename=" + new String(paramVO.getFileName().getBytes("utf-8"), "iso-8859-1"));
        try (ByteArrayOutputStream bos = templateService.excel(paramVO);
                BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream())) {
            out.write(bos.toByteArray());
            response.setHeader("Content-Length", String.valueOf(bos.toByteArray().length));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

2,前端頁面使用Ajax下載文件app

var xhr = new XMLHttpRequest();
        xhr.open('post', 'http://localhost:8080/user/export', true);
        xhr.responseType = 'blob';
        xhr.setRequestHeader('Content-Type', 'application/json;charset=utf-8');
        xhr.onload = function () {
            if (this.status == 200) {
                var blob = this.response;
                var a = document.createElement('a');
                var url = window.URL.createObjectURL(blob);
                a.href = url;
                //設置文件名稱
                a.download = '用戶信息.xls';
                a.click();
            }
        }
        xhr.send(JSON.stringify({
           "type" : 1,
           "startDate" : "2018-01-01",
           "endDate" : "2018-12-31"
        }));
    }

或者前端也能夠這樣實現:post

{
        var xhr = new XMLHttpRequest();
      xhr.open('post', 'http://localhost:8080/user/export', true);
      xhr.responseType = 'blob';
      xhr.onload = function () {
      var blob = this.response;
      if(window.navigator.msSaveOrOpenBlob){
          window.navigator.msSaveBlob(blob, 'msSaveBlob_testFile.txt');
      }else{
          var link = document.createElement('a');
          link.href = window.URL.createObjectURL(blob);
          link.download = 'msSaveBlob_testFile.txt';
          link.click();
          window.URL.revokeObjectURL(link.href);
      }
      xhr.send(null);
      }
}

 

本文轉自:https://blog.csdn.net/hj7jay/article/details/86309968this

相關文章
相關標籤/搜索