1. 程式人生 > >前端根據後端二進位制流生成檔案

前端根據後端二進位制流生成檔案

var url ="";

var data = {};

$http({
        url: url,
        method: 'post',
        data: data,
        responsetype: 'arraybuffer'
        })
.success(function (data) {
        var blob = new blob([data], {type: "application/vnd.ms-excel"});
        var objecturl = url.createobjecturl(blob);
        var aforexcel = $("<a><span class='forexcel'>下載excel</span></a>").attr("href", objecturl);
        $("body").append(aforexcel);
        $(".forexcel").click();
        aforexcel.remove();
})
.error(function () {
        alert("error");
})

但這種方式拿不到檔名。根據網上查詢,可以這麼做

1,後端設定

context.Response.Headers.Add("Access-Control-Expose-Headers", "Content-Disposition");
response.setHeader("content-disposition", "attachment;filename="+java.net.URLEncoder.encode(name, "UTF-8") + ".xlsx");

2,前端從headers中獲取,中文需要解碼,用decodeURIComponent

   var fileName = response.headers("Content-Disposition").split(";")[1].split("filename=")[1];
   var fileNameUnicode = response.headers("Content-Disposition").split("filename*=")[1];(編碼中文)
   if (fileNameUnicode) {
      fileName = decodeURIComponent(fileNameUnicode.split("''")[1]);
   }