I want to upload an image to the server using Ajax, but there is a problem. Would somebody please help me what is wrong here. I could submit the image using submit form but not ajax.here is my code:html:<div id="uploadPic" onclick="getFile()">Select a photo to upload</div><form name="myForm" id="avatar_form" enctype="multipart/form-data" method="post" action=""><div style='height: 0px;width:0px; overflow:hidden;'><input id="upfile" class="botpic" type="file" name="avatar" value="upload" required="" onchange="sub1()"></div></form>javascript:function getFile(){ document.getElementById("upfile").click();}function sub1(){var photo = document.getElementById("upfile"); var file = photo.files[0]; data = new FormData();data.append('file', file);$.ajax({ url: 'url', data: data enctype: 'multipart/form-data', processData: false, // do not process the data as url encoded params contentType: false, // by default jQuery sets this to urlencoded string type: 'POST', success: function ( output ) { document.getElementById('picTmp').innerHTML = output;; }});}PHP code:if (isset($_FILES["avatar"]["name"]) && $_FILES["avatar"]["tmp_name"] != ""){$fileName = $_FILES["avatar"]["name"]; $fileTmpLoc = $_FILES["avatar"]["tmp_name"];$fileType = $_FILES["avatar"]["type"];$fileSize = $_FILES["avatar"]["size"];$fileErrorMsg = $_FILES["avatar"]["error"];$kaboom = explode(".", $fileName);$fileExt = end($kaboom);list($width, $height) = getimagesize($fileTmpLoc); .......} 解决方案 Finally I found where the problem is. Maybe it is useful for others struggling with ajax uploading a file.Now it is working perfectly. The solution is:In the php code, all the ["avatar"] should be replaced with ["file"] as we are sending the file specified as file in ajax. 这篇关于使用ajax上传图像并提交表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
09-22 17:29