LoginSignup
40
43

More than 5 years have passed since last update.

HTML内で、クリックした時にファイルを開くのではなくダウンロードするようなボタンを作る

Last updated at Posted at 2016-02-01

クリックすることで、画像やPDF、テキストファイルなどをブラウザ上で開くのではなくダウンロードできるようにするボタンを作成したい。

下準備

予め、以下の様なファイルを作成しておく。

/var/www/html/php/download.php
<?php

 /* ディレクトリトラバーサル対策 */
 $DIR_PATH='/var/www/html';
 ini_set('open_basedir',$DIR_PATH);
 function get_name($str){
  if(strpos($str, '..') !== false){
    echo '相対パスは使用不可';
    exit();
  }
 return str_replace('\0','',$str);
 }
 $file=get_name(basename($_POST['dlfile']));  //ファイル名取得
 $dir=get_name(dirname($_POST['dlfile']));    //ディレクトリ名取得
 /* ディレクトリトラバーサル対策 */

 /* CSRF対策 */
 session_start();
 if(session_id() !==  $_POST['token']){
   echo '不正な処理です';
   exit();
 }
 /* CSRF対策 */

 chdir($DIR_PATH.$dir);      //当該ディレクトリに移動
 $mime_name=mime_content_type($file);  //ダウンロードするファイルのMIMEタイプを取得
 $file_length=filesize($file);
 header("Content-Disposition: attachment; filename=$file");
 header("Content-Length:$file_length");
 header("Content-Type:$mime_name");
 readfile($file);
?>

以上で下準備は完了。

実際にボタンを作成する

例えば
/var/www/html/content/file.pdf
がダウンロードできるようなボタンを
/var/www/html/hoge/fuga/index.html
上に作成したい場合には、

/var/www/html/hoge/fuga/index.html
  <?php session_start(); ?>
  <form action="/php/download.php" method='post'>
   <input name="dlfile" type="hidden" value="<?php echo htmlspecialchars('/content/file.pdf',ENT_COMPAT,'UTF-8'); ?>" />
   <input name="token"  type="hidden" value="<?php echo htmlspecialchars(session_id()       ,ENT_COMPAT,'UTF-8'); ?>" />
   <input type="submit" value='クイックダウンロード' />
  </form>

とすればよい。
スクリーンショット 2016-01-31 23.58.33.png
上記のようなボタンが作成されるはずである。
これをクリックすると、ファイルがブラウザ上で開かれず、代わりに
skitch.png
上記のようなウィンドウが表示され、直接ファイルをダウンロードできるはずである。

ボタンではなくて通常のリンクにしたい場合

スクリーンショット 2016-02-01 00.20.37.png
上記みたいにリンク形式にしたい場合は、

/var/www/html/hoge/fuga/index.html
 <?php session_start(); ?>  
  <form action="/php/download.php" method='post' name='formName'>
   <input name="dlfile" type="hidden" value="<?php echo htmlspecialchars('/content/file.pdf',ENT_COMPAT,'UTF-8'); ?>" />
   <input name="token"  type="hidden" value="<?php echo htmlspecialchars(session_id()       ,ENT_COMPAT,'UTF-8'); ?>" />
  </form>

  <a href="javascript:void(0)" onclick='document.formName.submit();return false;' >クイックダウンロード</a>

のように書き換える。

参考URL

http://www.webmagazine.kakisiti.co.jp/?p=690
http://e-words.jp/w/MIME%E3%82%BF%E3%82%A4%E3%83%97.html
http://d.hatena.ne.jp/kaitoh07/20090422/1240385880
http://qiita.com/addictionwhite/items/4e9c9cc4570c0bcaa656
http://qiita.com/mpyw/items/2f9955db1c02eeef43ea
http://www.sssg.org/blogs/hiro345/archives/14795.html

40
43
4

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
40
43