[英]Upload a file using PHP with Ajax
我正在嘗試使用AJAX和PHP上傳文件。
我已經使用表格完成了:
<form action="upload.php" method="POST">
<input type="file" id="idFile" name="fileName" />
</form>
而且效果很好,但是我真的需要使用AJAX來實現。
我已經有上傳文件的php腳本。 我希望該腳本通過AJAX執行。 我希望我的javascript函數執行以下操作:
function uploadFile(file) {
var url = "upload.php?file="+file; //<-- Can I do this?
xmlhttp = GetXmlHttpObject();
if (!xmlhttp) {
alert ("Browser does not support HTTP Request");
return;
}
var xml = xmlhttp;
xmlhttp.onreadystatechange = function () {
if (xml.readyState == 4) {
alert("THE FILE WAS UPLOADED");
}
};
xmlhttp.open("GET",url,true);
xmlhttp.send(null);
return true;
}
我的問題是:可以通過這種方式傳遞文件類型的變量嗎? 如果沒有,那我可以通過哪種方式傳遞文件變量? 我可以使用document.getElementById("idFile").value
嗎?
我希望有人可以幫助我,謝謝!
不幸的是,您無法使用Ajax上傳文件。 看看http://viralpatel.net/blogs/ajax-style-file-uploading-using-hidden-iframe/
我以這種方式解決了問題。
<form method="POST" id="formLic" name="formLic" enctype="multipart/form-data">
<label for="lnumero">Número: </label>
<input type="text" id="lnumero"/>
<label for="larchivo">Archivo: </label>
<input type="file" id="larchivo"/>
</form>
<script>
$(document).ready(function() {
$("form#formLic").submit(function(){
var formData = new FormData($(this)[0]);
$.ajax({
url: "nuevo/uploadInsert.php", // file where you save your data and files
type: 'POST',
data: formData,
async: false,
cache: false,
contentType: false,
processData: false,
success: function (result) {
// action or message
}
});
return false;
});
});
</script>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.