1

に問題がありnodejsます。ユーザーが要求したファイルを提供するサーバーを作成しています。私がしたこと:

  • 私はパスを取得します
  • ファイルを見つける ( fs.exists())
  • パスがファイルの場合、ストリームを取得します
  • stream.pipe (レスポンス)

今の問題は、ユーザーにファイルをダウンロードしてもらいたいのですが、.txtファイルを書くと、パイプメソッドはファイルの内容をブラウザに書き込む...ということで、.pdfで試してみましたが、これでWeb ページがロードされ続け、何も起こらない場合... 誰か助けてくれますか?

if(exists) {

        response.writeHead(302, {"Content-type":'text/plain'});

        var stat = fs.statSync(pathname);

        if(stat.isFile()) {
            var stream = fs.createReadStream(pathname);
            stream.pipe(response);
        } else {
            response.writeHead(404, {"Content-type":'text/plain'});
            response.end()
        }


        //response.end();

} else {
        response.writeHead(404, {"Content-type":'text/plain'});
        response.write("Not Found");
        response.end()
}
4

2 に答える 2

1

あなたのif場合、常にContent-Typeヘッダーをtext/plainに設定しているため、ブラウザはテキスト ファイルをインラインで表示します。そして、あなたの PDF の場合、text/plainは間違ったものです。そうでなければならないapplication/pdfので、タイプを動的に設定する必要があります。

ブラウザーでダウンロードを強制する場合は、次のヘッダーを設定します。

Content-Disposition: attachment; filename="your filename…"
Content-Type: text/plain (or whatever your content-type is…)

基本的に、これはExpress の res.download関数が内部的に行っていることなので、この関数も一見の価値があるかもしれません。

于 2013-10-25T13:09:52.510 に答える
1

well, looks like the problem is that the pdf content type isnt text/plain.

Replace the content type to application/pdf

like:

response.writeHead(302, {"Content-type":'application/pdf'});

More info here: http://www.iana.org/assignments/media-types and http://www.rfc-editor.org/rfc/rfc3778.txt

于 2013-10-25T13:11:44.233 に答える