HTML:如何使用ajax上傳文件?
<form id="confirmresourceform" enctype="multipart/form-data" method="post" style="display: none;">
<input id="uploadlecture" name="fileToUpload1" type="file" value="Upload Resources"/>
</form>
使用Javascript/jQuery的/阿賈克斯:
$("#submitchanges").on("click",function(){
//Upload files
var formData = new FormData(document.getElementById("confirmresourceform"));
formData.append('lecture', $('#uploadlecture')[0].files[0]);
$.ajax({
type: 'POST',
url: 'upload.php',
contentType: false,
processData: false,
data: formData,
success: function (data) {
console.log(data);
}
});
});
PHP(upload.php的):
echo $_FILES['lecture']['name'];
好了,所以我試圖上傳用ajax文件(在點擊一個div而不是使用提交表單的東西)。我已經通過jQuery將關鍵詞'lecture'添加到formdata中。目前,upload.php腳本有一行用於回顯文件名。然而,當阿賈克斯運行,並調用upload.php的,我得到以下錯誤:
Undefined index: lecture in C:\wamp\www\TheClass\lesson_creator_page\upload.php on line 4
我敢肯定,我在FORMDATA定義的「演講」,並通過了FORMDATA到PHP。有什麼我做錯了,是行formData.append('lecture', $('#uploadlecture')[0].files[0]);
正確嗎?
這可能會幫助你在這裏:http://stackoverflow.com/questions/6974684/how-to-send-formdata-objects-with-ajax-requests-in-jquery – Notaras