【问题标题】:Express Angular - Serve PDFExpress Angular - 提供 PDF
【发布时间】:2018-02-19 19:09:27
【问题描述】:

我正在开发一个 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());

【问题讨论】:

    标签: node.js angular http express pdf


    【解决方案1】:

    知道了!

    使用 fs.statSync('myFile.pdf').size 作为 Content-Length 效果很好。

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

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

    【讨论】:

      【解决方案2】:

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

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

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

      【讨论】:

      • 嗯...即使进行了此更改,输出中的文件仍然不可读。我已经添加了使用的中间件,也许其中一个干扰了我的传输?
      猜你喜欢
      • 2013-07-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-28
      • 2018-03-08
      • 2012-11-07
      • 2013-05-30
      • 1970-01-01
      相关资源
      最近更新 更多