[JavaScript]inputでファイル選択後即時アップ
inputでファイル選択後即時アップ。
[Twitter]tweet with mediaでも実装していました。jQuery.uploadを使います。
Sample ※Firefox,IE8,9で動作確認済
index.html
<!DOCTYPE html> <html lang="ja"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <meta http-equiv="Content-Script-Type" content="text/javascript"> <meta http-equiv="Content-Style-Type" content="text/css"> <title>ファイル選択後即時アップ</title> <meta name="description" content="****"> <meta name="keywords" content="****"> <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes"> <link rel="apple-touch-icon" href="apple-touch-icon.png"> <link rel="stylesheet" href="style.css" type="text/css"> <script type="text/javascript" src="jquery-1.9.1.min.js"></script> <script type="text/javascript" src="jquery.upload-1.0.2.min.js"></script> <script type="text/javascript" src="script.js"></script> </head> <body> <form method="post" action="" target="f1" enctype="multipart/form-data"> <input id="filebox" type="file" name="image" size="0" accept="image/*"/> </form> <ul id="preview"></ul> </body> </html>
script.js
$(function(){ set_thumaction(); }); function remove_thum(){ $('#preview').empty(); } function set_thumaction(){ $('#filebox').change(function() { var preview = $('#preview'); $(this).upload('upload.php',$("form").serialize(),function(html){ preview.append(html); },'html'); }); } function form_tweetmode(){ $('#filebox').remove(); $('form').attr('enctype','application/x-www-form-urlencoded'); } function restore_form(){ $('#fileboxwrap').html('<input id="filebox" type="file" name="image" size="0">'); $('form').attr('enctype','multipart/form-data'); set_thumaction(); }
upload.php
<?php if(isset($_FILES["image"])){ deleteFilesOfDir('./tmp'); $html='<li>'; $v=$_FILES["image"]; $ext=end(explode('.', $v["name"])); $filename='./tmp/'.time().'.'.$ext; $result = @move_uploaded_file( $v["tmp_name"], $filename); if($result){ $html .= '<img src="'.$filename.'" width="300"/><br/>'; }else{ $html .= 'エラー<br/>'; } foreach($_FILES["image"] as $key => $v){ $html .= $key.' : '.$v.'<br/>'; } $html .= '</li>'; echo $html; } function deleteFilesOfDir($dirPath){ if (!isset($dirPath)) { return; } $res_dir = opendir($dirPath); while( $file_name = readdir( $res_dir ) ){ if (is_dir($dirPath.'/'.$file_name)) { continue; } unlink($dirPath.'/'.$file_name); } closedir($res_dir); } ?>
jQuery.upload
http://lagoscript.org/jquery/upload