2014-03-25 114 views
0

有沒有辦法通過AJAX輸入onchange上傳圖片?我嘗試了多種方式,但他們不工作。我有以下代碼:AJAX onchange圖片上傳

$(document).ready(function (e) { 
    $("#uploadForm").on('submit',(function(e) { 
     e.preventDefault(); 
     $.ajax({ 
      url: "upload.php", 
      type: "POST", 
      data: new FormData(this), 
      contentType: false, 
      cache: false, 
      processData:false, 
      success: function(data) 
      { 
      $("#targetLayer").html(data); 
      }, 
      error: function() 
      { 
      }   
     }); 
    })); 
}); 
</script> 
</head> 
<body> 
<div class="bgColor"> 
<form id="uploadForm" method="post" name="uploadForm"> 
<div id="targetLayer">No Image</div> 
<div id="uploadFormLayer"> 
<label>Upload Image File:</label><br/> 
<input name="userImage" type="file" id="inputFile" /> 
<input type="submit" value="Submit" class="btnSubmit" /> 
</form> 

回答

1

您可以使用ajaxFileUpload插件。你可以使用下面的代碼結構;

$('#inputFile').change(function(){ 
    startUpload(); 
}); 

function startUpload(){ 
    $.ajaxFileUpload({ 
    url:'upload.php', 
    secureuri:false, 
    fileElementId:'inputFile', 
    dataType: 'json', 
    success: function(data,status){ 
     if(typeof(data.error) != 'undefined'){ 
      if(data.error){ 
       console.log(data.error); 
      }else{ 
       console.log("Image uploaded") 
      } 
     } 
    }, 
    error: function(data,status,e){ 
     console.log(e) 
    } 
    }); 
    return false; 
}