1. 程式人生 > >angularJs+NodeJs進行檔案下載

angularJs+NodeJs進行檔案下載

前提: 1,後臺nodejs在對應的介面中返回,需要下載的檔案的二進位制資料流。 2,前臺使用angularJs進行檔案下載。在下載的時候,使用Blob進行資料接收。 後臺路由實現:

let fileName = req.query.fileName,
        dirFile = path.join(__dirname,'../config/JsPatchFile/'+fileName),
        fReadStream;
    fs.exists(dirFile,function(exist) {
        if(exist){
            res.set({
                //"Access-Control-Expose-Headers":"Content-Disposition",//如果前臺獲取不到Content-Disposition這個引數,則需要這句話
                "Content-type":"application/octet-stream",
                "Content-Disposition":"attachment;filename="+encodeURI(fileName)
            });
            fReadStream = fs.createReadStream(dirFile);
            fReadStream.on("data",function(chunk){res.write(chunk,"binary")});
            fReadStream.on("end",function () {
                res.end();
            });
        }else{
            res.set("Content-type","text/html");
            res.send("file not exist!");
            res.end();
        }
    });

前臺angularJs實現:

$http({
                url: url,
                method: "GET",
                params: data,
                responseType: "blob"

            }).then(function (response, status, header, config, statusText) {
                var fileName = response.headers("Content-Disposition").split(";")[1].split("filename=")[1];
                fileName = decodeURI(fileName)//防止中文亂碼
                var blob = response.data;
                if ('msSaveOrOpenBlob' in navigator) {//IE匯出
                    window.navigator.msSaveOrOpenBlob(blob, fileName);
                }
                else {                   
                    var reader = new FileReader();
                    reader.readAsDataURL(blob);    // 轉換為base64,可以直接放入a表情href
                    reader.onload = function (e) {
                        // 轉換完成,建立一個a標籤用於下載
                        var a = document.createElement('a');
                        a.download = fileName;
                        a.href = e.target.result;
                        $("body").append(a);
                        a.click();
                        $(a).remove();
                    }
                }


            });