Express Angular - 提供PDF

时间:2017-09-11 13:55:07

标签: node.js angular http express pdf

我正在使用MEAN堆栈应用程序,并且我试图在前端(Angular)中显示来自后端(Express)的pdf。但每次,文件在传输过程中都会被破坏。有没有人有想法? 这是我的代码(简化):

后端:

import * as express from "express";
import * as fs from "fs";

myController.getPdf(req:express.Request, res:express.Response):void {
    res.setHeader('Content-Type', 'application/pdf');
    res.setHeader('Content-Length', fs.statSync('myPdf.pdf').size);
    fs.createReadStream('myPdf.pdf).pipe(res);
}

前端:

import {Http,ResponseContentType} from "@angular/http";

constructor(@Inject(Http) private _http:Http) {}

this._http.get('ENDPOINT', {responseType: ResponseContentType.ArrayBuffer})
    .map(response => {
        window.open(URL.createObjectURL(
            new Blob([response],{type:'application/pdf'})
))});

编辑:中间件:

import * as compression from "compression";
import * as zlib from "zbil";
import * as express from "express";
import * as bodyParser from "body-parser";
import * as session from "express-session";
import * as passport from "passport";
import * as morgan from "morgan";
import * as helmet from "helmet";

application: express.Application;
let _root = process.cwd();

application.use(compression({
    level: zlib.Z_BEST__COMPRESSION,
    threshold: "1kb"
}));
application.use(express.static(_root + "/node_modules/"));
application.use(express.static(_root + "/jspm_packages/"));
application.use(express.static(_root + "/client/dev/"));
application.use(bodyParser.json());
application.use(session({
    secret: 'abcd',
    saveUnitialized: true,
    resave: true,
}));
application.use(passport.initialize());
application.use(passport.session());
application.use(morgan("dev"));
application.use(helmet());

2 个答案:

答案 0 :(得分:1)

知道了!

使用fs.statSync(' myFile.pdf')。尺寸作为Content-Length运作良好。

问题出在另一端:响应必须映射到blob()函数:

this._http.get(ENDPOINT, {responseType: ResponseContentType.ArrayBuffer})
    .map(response => {
        window.open(URL.createObjectURL(
            new Blob(response.blob(), {type:'application/pdf'}));
    });

答案 1 :(得分:0)

我认为,您的“Content-Length”标头无效。文件系统的size方法返回字符串长度。

某些UTF-8字符包含多个字节。

更好的方法是使用http://nodejs.org/api/buffer.html中的Buffer.byteLength(string,[encoding])。这是一个类方法,因此您不必创建任何Buffer实例。