0
我的目標是將一些圖像上傳到服務器併爲其提供描述。發佈數據服務器端並在提交表單時執行javascript代碼
在點擊的上傳按鈕,這就是我希望發生的:
1)javascript函數動態地將形式來獲得圖像的描述 。在提交表單
2):
a) the description entered in the form must be available $_POST['description'] at server side. b) the images are sent to the server using an XMLHttpRequest
在我寫的描述中的代碼是不可$_POST['description']
。 當我刪除檢查if(!isset($_POST['description']))
,圖像文件完美上傳。 這是我的代碼:
JavaScript代碼
upload.onclick = uploadPrompt;
// dynamically add a form
function uploadPrompt() {
// fileQueue is an array containing all images that need to be uploaded
if (fileQueue.length < 1) {
alert("There are no images available for uploading.");
} else {
var inputDescription = document.createElement("input");
inputDescription.className = "promptInput";
inputDescription.type = "text";
inputDescription.name = "description";
var inputButton = document.createElement("button");
inputButton.id = "promptInputButton";
inputButton.type = "submit";
inputButton.innerHTML = "Start uploading";
var promptForm = document.createElement("form");
promptForm.method = "post";
promptForm.action = "upload.php";
promptForm.onsubmit = uploadQueue;
promptForm.id = "promptForm";
promptForm.appendChild(inputDescription);
promptForm.appendChild(inputButton);
document.body.appendChild(promptForm);
}
}
function uploadQueue(ev) {
ev.preventDefault();
elementToBeRemoved = document.getElementById("promptForm");
elementToBeRemoved.parentElement.removeChild(elementToBeRemoved);
while (fileQueue.length > 0) {
var item = fileQueue.pop();
// item.file is the actual image data
uploadFile(item.file);
}
}
function uploadFile (file) {
if (file) {
var xhr = new XMLHttpRequest();
var fd = new FormData();
fd.append('image',file);
xhr.upload.addEventListener("error", function (ev) {
console.log(ev);
}, false);
xhr.open("POST", "upload.php");
xhr.setRequestHeader("Cache-Control", "no-cache");
xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
xhr.setRequestHeader("X-File-Name", file.name);
xhr.send(fd);
}
}
PHP代碼upload.php的
<?php
session_start();
if (!isset($_POST['description'])) {
echo "upload:fail\n";
echo "message:No scene was specified";
exit();
}
if (isset($_FILES['image'])) {
if(!move_uploaded_file($_FILES['image']['tmp_name'], "uploads/" . $_POST['description'] . "/" . $_FILES['image']['name'])) {
echo "upload:fail\n";
}
else {
echo "upload:succes\n";
}
exit();
}
exit();
?>
我意識到我的代碼是垃圾,我意識到您提供的選項。雖然上傳只是我試圖製作的應用程序的一部分。您建議的'serialize()'方法對我有很大幫助!謝謝!! – user1879060 2013-02-16 15:40:00
還有什麼需要幫助的嗎?否則,您可以通過接受答案將此問題標記爲已關閉 - 這將有助於您的接受評級 – hohner 2013-02-16 15:41:37