LoginSignup
14
10

More than 5 years have passed since last update.

javascript、iframeでファイルのダウンロード

Last updated at Posted at 2015-01-08

ダウンロードボタンを押すとファイルがダウンロードされる。
ただし、ファイルが存在しない場合はエラーメッセージをモーダルで表示させる方法のめも。

sample.js
//ダウンロード先のURL
var url = '/download';
var iframes = "<iframe id="downloader" width="0" height="0" frameborder="0" src="' + url + '"/>";
$(iframes).appendTo('body').load(function(){
    //エラーがあった場合、サーバー側からエラーメッセージが返されるので、それを表示
    var body = $(this).contents().find('body').text();
    if(body != ''){
        alert(body);
    }
    //iframeは自動的に閉じる
    setTimeout(function() {
        $('#downloader').remove();
    },300);
});
14
10
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
14
10