2

エクスプレス アプリケーションを作成していますが、ユーザーが [ダウンロード] をクリックしたときにファイルをエクスポートできません。

コンテンツを使用してサーバーに ajax リクエストを送信し、サーバー上でファイルを作成してファイル パスを送り返すという私のアプローチ。そこからsrc、要素の属性をiframeファイル パスで調整します。

しかし、Chrome (または実際には任意のブラウザー) では何も起こりません。インスペクターのネットワークタブを見ると、ファイルを正常に受信したことが示され (応答コードは 200 で)、コンテンツはそこにあります。また、 にiframeは正しい がありますsrc。ダウンロード ダイアログをポップアップ表示したいのですが、表示されません。

何か案は?ありがとうございました!


コード例:

app.js (サーバー)

app.post('/create-html', function(req, res) {

    // explicitly set the headers on the server
    res.header('Content-Type', 'application/octet-stream');
    res.header('Content-Disposition', 'attachment; filename="test.html"')

    var html      = req.body.content
       , name      = "test.html"
       , filepath  = (__dirname + "/public/files/" + name)
       , json_resp = {
            data: ''
          , err: false
         };

    fs.writeFile( filepath, html, 'utf8', function(err, data) {
        // write the file and res.send the json_resp, so we can
        // access the filename on the client
    })
})

script.js (クライアント)

$("#export-html").click( function(e) {
    e.preventDefault();
    var html = $("#html-wrapper").html(); // the html of the file we want to make

    $.ajax({
          method: "POST"
        , url: "/create-html"
        , headers: {
            "Content-Disposition": 'attachment; filename="test.html"'
          }
        , type: "JSON"
        , success: function(resp) {
              var iframe = document.getElementById("iframe")
                , fp_prefix = "/files/"
                , fp = fp_prefix + resp.data; // ex: "/files/test.html" - the path where the file can be accessed

              iframe.src = fp
          }
    })

})

200サーバーに POST するとき ( /create-html)、およびサーバーがデータを送り返すとき( )にs が返されますtest.html。ファイルの内容がtest.htmlWeb インスペクターに表示され/files/test.html、ページが表示されます。しかし、HTML をダウンロードすることはできません

何か案は?

4

1 に答える 1

1

ExpressJS では、これを使用します。

apt.get('/create-html', function (req, res) {
  var name       = "test.html"
      , filepath = (__dirname + "/public/files/" + name);

  res.download(filepath, name);
});
于 2013-04-03T23:17:19.750 に答える