表达角 - 服务PDF



我正在使用平均堆栈应用程序,并且我正在尝试在前端(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'})
))});

编辑:Middlewares:

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());

得到它!

使用fs.statsync('myfile.pdf')。大小作为内容长度效果很好。

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

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

我认为,您的"内容长度"标头无效。文件系统返回字符串长度的大小方法。

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

更好的方法是从http://nodejs.org/api/buffer.html使用buffer.bytelength(string,[编码])。这是一种类方法,因此您不必创建任何缓冲区实例。

最新更新