前端index.html代码:
<!DOCTYPE html> <html lang="en" > <head> <meta charset="utf-8" /> <title>Pure HTML5 file upload | Script Tutorials</title> <link href="css/main.css" rel="stylesheet" type="text/css" /> <script src="js/script.js"></script> </head> <body> <header> <h2>Pure HTML5 file upload</h2> <a href="http://www.script-tutorials.com/pure-html5-file-upload/" class="stuts">Back to original tutorial on <span>Script Tutorials</span></a> </header> <div class="container"> <div class="contr"><h2>You can select the file (image) and click Upload button</h2></div> <div class="upload_form_cont"> <form id="upload_form" enctype="multipart/form-data" method="post" action="upload.php"> <div> <div><label for="image_file">Please select image file</label></div> <div><input type="file" name="image_file" id="image_file" onchange="fileSelected();" /></div> </div> <div> <input type="button" value="Upload" onclick="startUploading()" /> </div> <div id="fileinfo"> <div id="filename"></div> <div id="filesize"></div> <div id="filetype"></div> <div id="filedim"></div> </div> <div id="error">You should select valid image files only!</div> <div id="error2">An error occurred while uploading the file</div> <div id="abort">The upload has been canceled by the user or the browser dropped the connection</div> <div id="warnsize">Your file is very big. We can't accept it. Please select more small file</div> <div id="progress_info"> <div id="progress"></div> <div id="progress_percent"> </div> <div class="clear_both"></div> <div> <div id="speed"> </div> <div id="remaining"> </div> <div id="b_transfered"> </div> <div class="clear_both"></div> </div> <div id="upload_response"></div> </div> </form> <img id="preview" /> </div> </div> </body> </html>
后端php代码:
<?php function bytesToSize1024($bytes, $precision = 2) { $unit = array('B','KB','MB'); return @round($bytes / pow(1024, ($i = floor(log($bytes, 1024)))), $precision).' '.$unit[$i]; } $sFileName = $_FILES['image_file']['name']; $sFileType = $_FILES['image_file']['type']; $sFileSize = bytesToSize1024($_FILES['image_file']['size'], 1); echo <<<EOF <p>Your file: {$sFileName} has been successfully received.</p> <p>Type: {$sFileType}</p> <p>Size: {$sFileSize}</p> EOF;js和css文件在包里。整个示例程序打包从这里下载:html5+php上传示例源代码