У меня возникают проблемы при попытке загрузить файлы, используя последнюю версию XHR 2 вместе с PHP.
Мой код выглядит следующим образом:
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 (я не был уверен насчет кода PHP и нашел ниже в этой статье 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";
Я получаю сообщение об успехе, нофайлы не загружены в соответствующую папку. Я думаю, что либо formdata
не хранится должным образом через JavaScript, либо он не передается на сервер должным образом для доступа PHP (или это может быть тот код PHP, который я взял изэта статья, ссылка на которую приведена выше, просто не работает - поскольку я не PHP-человек, я не уверен на 100%).
Любая помощь будет принята с благодарностью.
С уважением,Mark