HTML5 Image upload with javascript and php
I want to multi-upload images to a database using javascript and php (html5), but I have problem with it, my code is just uploading one image, which is the latest photo selected and not all. How can fix this problem and what do I have to do?
I use developer mozilla html5: Here
You can test my code by selecting multi images and clicking on button Upload Image to see the result.
DEMO FROM MY FULL CODDE
My js code:
- function doClick() {
- var el = document.getElementById("fileElem");
- if (el) {
- el.click();
- }
- }
- function handleFiles(files) {
- var d = document.getElementById("fileList");
- if (!files.length) {
- d.innerHTML = "<p>No files selected!</p>";
- } else {
- var list = document.createElement("ul");
- d.appendChild(list);
- for (var i = 0; i < files.length; i++) {
- var li = document.createElement("li");
- list.appendChild(li);
- var img = document.createElement("img");
- img.src = window.URL.createObjectURL(files[i]);;
- img.height = 60;
- img.onload = function () {
- window.URL.revokeObjectURL(this.src);
- }
- li.appendChild(img);
- var info = document.createElement("span");
- info.innerHTML = files[i].name + ": " + files[i].size + " bytes";
- li.appendChild(info);
- }
- }
- }
My php code:
- <?php
- foreach ($_FILES[ 'userfile'] as $key=>$value{
- echo '<pre>';
- print_r($value);
- }
- ?>
My html code:
- <html>
- <head>
- <title>file input click() demo</title>
- <script type="text/javascript" src="html5java.js"></script>
- </head>
- <body>
- <a href="javascript:doClick()">Select some files</a>
- <div id="fileList"></div>
- <form action="up.php" method="post" enctype="multipart/form-data">
- <input type="file" name="userfile[]" id="fileElem" multiple accept="image/*"
- style="display:none" onchange="handleFiles(this.files)">
- <input type="submit" value="Upload Images">
- </form>
- </body>
- </html>