HTML5 Multi-File Upload example

Source: Internet
Author: User
Tags file upload

Research for half a day to find HTML5 is actually particularly simple.

Dotou control <input id= "fileimage" type= "file" size= "" name= "files[" multiple
multiple This input feature is HTML5 new, so IE6 is not compatible with such low-level goods.

This property is equivalent to the previous multiple-graph scenario

The code is as follows Copy Code
<input id= "fileimage" type= "file" size= "" Name= "files[" ">
<input id= "fileimage" type= "file" size= "" Name= "files[" ">
<input id= "fileimage" type= "file" size= "" Name= "files[" ">

But the truth is simple. One can only choose one picture at a time

HTML5 This can select multiple pictures, pull the wind ah.

The background code does not change.

The code is as follows Copy Code

function Getimgmany ($RR, $upload _image_dir)
{
$fs = $_files[$RR];
$imgnames = Array ();

For ($i =0 $i <count ($fs [' name ']); $i + +)
{
Get extension

$pathinfo = PathInfo ($_files[$rr] [' name '] [$i]);

if ($fs [' Size ']==0) continue;

Check the file name extension to see if it is a supported picture format
$fileextname = "Jpg|gif|png|jpeg|bmp";
if ($type = = "File")
{
$fileextname. = "|txt|sql|html|htm|pdf|chm|rar|zip|doc|xls";
}
echo $pathinfo ["extension"];
if (!preg_match ("/^". $fileextname. " $/i ", $pathinfo [" extension "])
{
echo "<div style= ' font-size:12px;color=red;font-weight:bold; ' > Unsupported extension <a href= ' Javascript:history.back (-1); ' > Click return </a></div> ";
Exit ();
}

Srand (Double) microtime () * 948625);

Generate Random file names
$targetname =time ();
$targetname. = rand (). '.' . $pathinfo ["extension"];

$targetpath = $upload _image_dir. Strftime ("%y%m", Time ()). /". $targetname;
Copy ($_files[$rr] [' tmp_name '] [$i], $targetpath);
Unlink ($_files[$rr] [' tmp_name '] [$i]);

$imga = $targetpath;
Array_push ($imgnames, $IMGA);
}
return $imgnames;
}

Code calls
PHP-Side code

The code is as follows Copy Code

$imgdir = "uploads/";
$imgs = Getimgmany (' Files ', $imgdir);
Print_r ($IMGS);

Let's look at an AJAX example.

HTML5 Ajax upload Image code is as follows:

The code is as follows Copy Code

<! DOCTYPE html>

<meta http-equiv= "Content-type" content= "text/html; Charset=utf-8 ">

<TITLE>HTML5 Upload Pictures </title>

<style type= "Text/css" >

Li{list-style:none}

Li img{width:100px}

. tips{color:red}

</style>

<body>

<p> Note that the picture is too small to see the progress bar </p>

<input type= "File" id= "Filesinput" multiple/>

<br><br>

<a href= "javascript:;" id= "Btnupload" > Start uploading </a>

<p id= "Info" ></p>

<label> Read progress: </label><progress id= "Progress" value= "0" max= "></progress>"

<span id= "percent" ></span>

<p id= "Uploadspeed" ></p>

<ul id= "Imagebox" ></ul>

<script type= "Text/javascript" >

Define methods to get objects

function $ (ID) {

return document.getElementById (ID);

}

var filesinput = $ ("Filesinput"),

Info = $ ("info"),

Imagebox = $ ("Imagebox"),

Btnupload = $ ("Btnupload"),

Progress = $ ("Progress"),

Percent = $ ("percent"),

Uploadspeed = $ ("Uploadspeed");

Defines an array that holds picture objects

var uploadimgarr = [];

To prevent the image upload completed, and then click the Upload button to repeat the upload picture

var isupload = false;

Defines a function to get picture information

function GetFiles (e) {

Isupload = false;

E = e | | window.event;

Get a list of picture information in file input

var files = e.target.files,

Verify the regular of the picture file

reg =/image/.*/i;

Console.log (files);

for (var i = 0,f; f = files[i]; i++) {

After you remove this if, you can also upload other files

if (!reg.test (F.type)) {

imagebox.innerhtml = "<li> you selected" + F.name + "file is not a picture </li>";

Jump out of the loop

Continue

}

Console.log (f);

Uploadimgarr.push (f);

var reader = new FileReader ();

Reader.onload = (function (file) {

Get picture-related information

var fileSize = (file.size/1024). toFixed (2) + "K",

FileName = File.name,

FileType = File.type;

Console.log (FileName)

return function (e) {

Console.log (E.target)

Get the width and height of a picture

var img = new Image ();

Img.addeventlistener ("Load", imgloaded, false);

IMG.SRC = E.target.result;

function imgloaded () {

ImgWidth = Img.width;

ImgHeight = Img.height;

The picture is loaded to get imgwidth and ImgHeight

imagebox.innerhtml + + <li> The name of the picture is: "+ FileName +"; The size of the picture is: "+ fileSize +"; The type of picture is: "+ FileType +"; The size of the picture is: "+ imgwidth +" X "+ imgheight +" </l I> ";

}

}

}) (f);

Read File contents

Reader.readasdataurl (f);

}

Console.log (Uploadimgarr);

}

if (window. File && window. FileList && windows. FileReader && windows. Blob) {

Filesinput.addeventlistener ("Change", GetFiles, false);

} else {

info.innerhtml = "Your browser does not support HTML5 long passes";

Info.classname= "Tips";

}
Start uploading photos

function Uploadfun () {

var j = 0;

function Fun () {

if (uploadimgarr.length > 0 &&!isupload) {

var singleimg = uploadimgarr[j];

var xhr = new XMLHttpRequest ();

if (xhr.upload) {

progress bar (see http://www.css119.com/archives/1476)

Xhr.upload.addEventListener ("Progress",

Function (e) {

if (e.lengthcomputable) {

Progress.value = (e.loaded/e.total) * 100;

percent.innerhtml = Math.Round (e.loaded * 100/e.total) + "%";

Calculate speed

var nowdate = new Date (). GetTime ();

var x = (e.loaded)/1024;

var y = (nowdate-startdate)/1000;

uploadspeed.innerhtml = "Speed:" + (x/y). toFixed (2) + "k/s";

} else {

percent.innerhtml = "Cannot calculate file size";

}

},

FALSE);

File upload success or failure

Xhr.onreadystatechange = function (e) {

if (xhr.readystate = = 4) {

if (Xhr.status = && eval ("+ Xhr.responsetext +")). Status = = True) {

Info.innerhtml + + singleimg.name + "upload complete;";

Because the progress event is to return the data for a certain period of time, so the individual progress cannot be 100%, forcing the setting after this setting is passed 100%

Progress.value = 100;

percent.innerhtml = "100%";

Isupload = true;

} else {

info.innerhtml + = Singleimg.name + "upload failed;";

}

Upload a successful (or failed) one, call the fun function again, simulate the loop

if (J < uploadimgarr.length-1) {

j + +;

Isupload = false;

Fun ();

}

}

};

var formdata = new Formdata ();

Formdata.append ("Filedata", singleimg);

Start uploading

Xhr.open ("POST", "upload.php", true);

Xhr.send (Formdata);

var startdate = new Date (). GetTime ();

}

}

}

Fun ();

}

Btnupload.addeventlistener ("Click", Uploadfun, false);

</script>

</body>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.