2012-06-18 7 views
2

빠른 응용 프로그램을 만들고 있는데, 사용자가 "다운로드"를 클릭 할 때 파일을 내보내는 데 문제가 있습니다.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 
      } 
    }) 

}) 

내가 g 해요 서버에 게시 할 때 (/create-html), 서버가 데이터를 다시 보낼 때 (test.html) 200. test.html 파일의 내용이 웹 속성에 표시되고 /files/test.html으로 이동하면 페이지가 표시됩니다. 그러나, 나는을 다운로드 할 수 없다.

아이디어가 있으십니까? 당신이 사용 ExpressJS와

+0

은 예 또는 코드가 있습니까? –

+1

돌아 오는 콘텐츠를 살펴보고 올바른 HTTP 응답 헤더가 있는지 확인하십시오. Content-Disposition : attachment; filename = <파일 이름. 텍스트>. 또한 파일 다운로드를 돕기 위해 만든 플러그인을 사용해 볼 수도 있습니다. 그것은 iframe도 사용하고 잘 테스트되었습니다 : http://johnculviner.com/post/2012/03/22/Ajax-like-feature-rich-file-downloads-with-jQuery-File-Download.aspx –

+0

@ JohnCulviner에 대한 메모. 익스프레스의 응답 객체에서이 헤더를 사용하고 있습니다. Inspector에서도 확인할 수 있습니다. 다른 아이디어가 있습니까? – Connor

답변

1

:

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

    res.download(filepath, name); 
}); 
관련 문제