簡體   English   中英

下載文件不適用於iframe

[英]Download file not working with iframe

我正在制作一個快速申請,當用戶單擊“下載”時無法導出文件。

我的方法是向服務器發出含內容的ajax請求,然后在服務器上創建文件並發送回文件路徑。 從那里,我用文件路徑調整iframe元素的src屬性。

但是,Chrome(實際上沒有任何瀏覽器)上沒有任何反應。 如果查看檢查器的“ 網絡”選項卡,則表明它已收到OK(帶有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
          }
    })

})

POST到服務器( /create-html )以及服務器向后發送數據( test.html )時,我得到200 s。 test.html文件的內容顯示在Web檢查器中,轉到/files/test.html顯示該頁面。 但是, 我無法下載HTML

有任何想法嗎?

與ExpressJS一起使用:

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

  res.download(filepath, name);
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM