2016-10-10 6 views
1

私はストリームを応答に送るときに強制的にダウンロードする方法はありますか? 私はクロームツールに見れば、私は細かいヘッダと、レスポンスがOKであることを参照してください。ノード/エクスプレス:stream.pipe()のダウンロードがありません

HTTP/1.1 200 OK 
Server: Cowboy 
Connection: keep-alive 
X-Powered-By: Express 
Content-Type: application/pdf 
Date: Mon, 10 Oct 2016 20:22:51 GMT 
Transfer-Encoding: chunked 
Via: 1.1 vegur 
Request Headers 
view source 

私もきめ細かい対応でPDFファイルのコードを参照してください、ないファイルのダウンロードが開始されていません。多分私は何かが恋しいですか?あなたがダウンロードする必要があるという添付コンテンツがあることをブラウザに知らせるためにContent-Dispositionヘッダーを追加する必要が

router.post('/reports/create', access.Regular, function (req, res, next) { 
    ... 

    pdf.create(html).toBuffer(function(err, buffer){ 
     res.writeHead(200, { 
      'Content-Type': 'application/pdf', 
      'Content-Disposition': 'attachment; filename=some_file.pdf', 
      'Content-Length': buffer.length 
     }); 
     res.end(buffer) 
    }); 
}); 
+0

あなたのコードは何ですか?どのようにサーバーに接続していますか? – Frxstrem

+0

私は普通の表現パターン 'app.post(...)'を以下のように使用します – AlexNasonov

+0

私はブラウザでどのように接続するのですか?あなたは 'XMLHttpRequest'や' $ .ajax'や 'fetch'のようなものを使ってリクエストしていますか? – Frxstrem

答えて

0

ルート上の私のコードは次のようになります。

app.get('/:filename', (req, res) => { 
    // Do whatever work to retrieve file and contents  

    // Set Content-Disposition Header on the response 
    // filename is the name of the file the browser needs to download when 
    // receiving the response to this particular request 
    res.setHeader('Content-Disposition', `attachment; filename=${req.params.filename}`); 

    // stream the fileContent back to the requester 
    return res.end(fileContent) 
}); 
+0

ストリームまたはバッファーを持っています。特定のファイルではありません。 – AlexNasonov

+0

@AlexNasonov、私の例では、fileContentはストリームまたはバッファです。あなたの応答に 'Content-Disposition'ヘッダーがないということです。基本的には、そのヘッダはブラウザにあなたがデータのストリーム/バッファを返したことを伝え、ヘッダの 'filename'値の中にその名前でダウンロードされるべきです。 – peteb

+0

res.setHeader( 'Content-type'、 'application/pdf'); res.setHeader ... pdf.create(html、options).toStream(function(err、stream){ stream.pipe(res); このファイルには、次のファイルが含まれています。同じ問題 - 私はコンソールからのデータを参照していますが、ファイルはダウンロードされません。 – AlexNasonov

0

それはこのように私の作品:

var html = '<h1>Hello World</h1>'; 
let options = { 
    format: 'Letter', 
    border: '1cm' 
}; 
pdf.create(html, options).toBuffer(function (err, Buffer) { 
     if (err) { 
      res.json({ 
      data: 'error PDF' 
      }) 
     } else { 
      res.set({ 
       'Content-Disposition': 'attachment; filename=test.pdf', 
       'Content-Type': 'application/pdf; charset=utf-8' 
      }); 
      res.write(Buffer); 
      res.end(); 
     } 
    }); 
関連する問題