AJAX onchange图片上传

时间:2014-03-25 12:05:36

标签: javascript php jquery ajax

有没有办法通过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 个答案:

答案 0 :(得分: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;
}