最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Upload image using ajax and form submitting - Stack Overflow

programmeradmin0浏览0评论

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

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);
 .......
}
Share Improve this question asked Jun 5, 2014 at 19:32 AhadAhad 371 gold badge1 silver badge7 bronze badges 3
  • Are you getting server-side or client-side errors? – twinlakes Commented Jun 5, 2014 at 19:35
  • It seems the it send the data to the server, but it cannot get into the if (isset..). I tested the php code without ajax buy regular submitting the form. everything works fine. The image updates properly, but the page needs to be refreshed to show the updated image. So, I am going to use ajax, but cannot do that at all. – Ahad Commented Jun 5, 2014 at 19:48
  • use var_dump function to inspect request variables. var_dump($_POST); var_dump($_FILES); and things get clear. – Shonhloi Shon Commented Sep 1, 2019 at 17:15
Add a ment  | 

5 Answers 5

Reset to default 0

The first thing I notice is that you're missing a ma 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 ment!"); 
}); 

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.

发布评论

评论列表(0)

  1. 暂无评论