简体   繁体   中英

Upload image using ajax and form submitting

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);
 .......
}

The first thing I notice is that you're missing a comma after the data parameter declaration. That might be your only issue.

$.ajax({
    url: 'url',
    data: data,
    enctype: 'multipart/form-data',
    //etc...

What's the name of your PHP script? That's what you should specify as 'url':

url: 'script_name.php',

Maybe this plugin could help you

Jquery Form

I had a lot of problem making from myself and with this plugin everething works, just try, this

$('form').ajaxForm(function() { 
    alert("Thank you for your comment!"); 
}); 

I would guess that without using preventDefault() method in your script, you submit the form to the same page using action="" and method="post" , thus never entering your $.ajax() ;

I've done something like this

$('#query_projects').submit(function(event){
    event.preventDefault();
    var formData = new FormData($(this)[0]);            

    var request = $.ajax({
        type: 'POST',
        url: 'query_tab_projets.php',
        mimeType:'application/json',
        dataType:'json',
        data: formData,
        contentType: false,
        processData: false,
        success: function(data){                            
            alert(JSON.stringify(data,null,4));
        },
        error: function(msg){
            alert(JSON.stringify(msg,null,4));
        }
    });             
});

where #query_projects is my form id

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM