I’m having problems trying to upload files using the latest XHR 2 along with PHP.
My code is as follows:
HTML…
<!doctype html>
<html>
<head>
<title>XHR Multiple File Upload</title>
<link rel="stylesheet" type="text/css" href="upload.css">
</head>
<body>
<input type="file" id="upload" multiple="true" accept="image/*">
<a href="#" id="upload-link">Click here to upload multiple files</a>
<script src="upload.js"></script>
</body>
</html>
JavaScript
var formdata, link, input, doc = document;
if (window.FormData) {
formdata = new FormData();
}
function init(){
link = doc.getElementById("upload-link"),
input = doc.getElementById("upload");
link.addEventListener("click", process, false);
input.addEventListener("change", displaySelectedFiles, false);
}
function process (e) {
// If the input element is found then trigger the click event (which opens the file select dialog window)
if (input) {
input.click();
}
e.preventDefault();
}
function displaySelectedFiles(){
// Once a user selects some files the 'change' event is triggered (along with this listener function)
// We can access selected files via 'this.files' property object.
var files = this.files,
count = 0,
len = files.length;
while (count < len) {
createImage(files[count]);
count++;
}
var confirm = doc.createElement("input");
confirm.type = "submit";
confirm.value = "Upload these files";
confirm.id = "confirm";
doc.body.appendChild(confirm);
confirm.addEventListener("click", uploadFiles, false);
}
function createImage (file) {
var element = doc.createElement("img");
element.file = file;
element.classList.add("thumbnail");
// We store the file object as a property of the image (for use later)
doc.body.appendChild(element);
// The FileReader object lets web applications asynchronously read the contents of files
var reader = new FileReader();
reader.onload = (function (img) {
return function (e) {
img.src = e.target.result;
};
})(element);
reader.readAsDataURL(file);
}
function uploadFiles(){
var reader = new FileReader(),
imgs = doc.querySelectorAll(".thumbnail"),
count = 0,
len = imgs.length;
while (count < len) {
// Once image file is read then we can 'send' the upload request
reader.onload = function (e) {
formdata.append("images[]", e.target.result);
}
reader.readAsDataURL(imgs[count].file);
count++;
}
fileUpload();
}
function fileUpload(){
var xhr = new XMLHttpRequest();
function progressListener (e) {
console.log("progressListener: ", e);
if (e.lengthComputable) {
var percentage = Math.round((e.loaded * 100) / e.total);
console.log("Percentage loaded: ", percentage);
}
};
function finishUpload (e) {
console.log("Finished Percentage loaded: 100");
};
// XHR2 has an upload property with a 'progress' event
xhr.upload.addEventListener("progress", progressListener, false);
// XHR2 has an upload property with a 'load' event
xhr.upload.addEventListener("load", finishUpload, false);
// Begin uploading of file
xhr.open("POST", "upload.php");
xhr.onreadystatechange = function(){
console.info("readyState: ", this.readyState);
if (this.readyState == 4) {
if ((this.status >= 200 && this.status <= 200) || this.status == 304) {
if (this.responseText != "") {
console.warn(xhr.responseText);
}
}
}
};
xhr.send(formdata);
}
window.addEventListener("DOMContentLoaded", init, false);
PHP (I wasn’t sure about the PHP code and found the below via this article http://net.tutsplus.com/tutorials/javascript-ajax/uploading-files-with-ajax/)
foreach ($_FILES["images"]["error"] as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
$name = $_FILES["images"]["name"][$key];
move_uploaded_file( $_FILES["images"]["tmp_name"][$key], "uploaded-images/" . $_FILES['images']['name'][$key]);
}
}
echo "Successfully Uploaded Images";
I get the success message back, but no files uploaded into the relevant folder. I think either the formdata isn’t being stored properly via JavaScript OR it isn’t being passed to the server properly for PHP to access (or it could be that the PHP code I grabbed from that article linked to above just doesn’t work – as I’m not a PHP person I’m not 100% sure).
Any help would be greatly appreciated.
Kind regards,
Mark
The main issue was with how I was appending the image file object to the FormData object.
A working version of the code can be found below and also on GitHub here: https://github.com/Integralist/XHR2-Multiple-File-Upload–with-PHP-
HTML
PHP
JavaScript