2

我正在使用 jquery ajax 方法从 php 上传文件。我在单击按钮时使用提交表单实现了文件上传,但是当输入字段更改时,它不适用于 onchange 事件。这是我正在使用的代码,

<div id="photo">
<img id="image" src="<?php echo $uploadedfile;?>" width=100% height=100%>
</div>
<form id="myform" method="post" enctype="multipart/form-data">
<div id="pick">Change Photo
<input type="file" name="files" id="upload">
</div>
<input type="submit" value="send" name="submit">
</form>

使用的jQuery

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>

$("form#myform").submit(function(event){

event.preventDefault();

var formData = new FormData($(this)[0]);

$.ajax({

url : "main.php",
type: 'POST',
datatype : "JSON",
data: formData,
async: false,
cache: false,
contentType: false,
processData: false,
success: function (returndata) {

    $("#image").attr({
        'src' : returndata.uploadedfile
});

}
}); 
return false;

});

</script>

php代码在这里

<?php   
$uploadedfile = "default.jpg";
if(isset($_POST['submit'])){

if(isset($_FILES["files"]["name"])){


$filename = $_FILES["files"]["name"];   
$tmppath  = $_FILES["files"]["tmp_name"];
$ext = pathinfo($filename,PATHINFO_EXTENSION);

$targetfile = "uploads/".basename($filename);

if($_FILES["files"]["size"] > 0)
{

if($ext == "jpg")
{
if(file_exists($targetfile)){

$uploadok = false;
$error = "file already exists";
}
else {

$uploadok = true;
}
}
else
{

$uploadok = false;
$error = "only jpg format is allowed";
}   
}
else {
$uploadok = false;
$error = "filesize is too short";   
}
if($uploadok == true){  
move_uploaded_file($tmppath,$targetfile);

$uploadedfile = $targetfile;
$error = "no errors!";
}else{
$uploadedfile = "default.jpg";
}
header("Content-type: text/x-json");
$data = array('error'=>$error, 'uploadedfile'=>$uploadedfile);

echo json_encode($data);
exit();
}
}
?>

我想通过更改而不是通过单击按钮来实现这一点。任何想法 ??

4

1 回答 1

1

改变这个:

$("form#myform").submit(function (event) 

对此:

$("form#myform").change(function (event) 
于 2015-09-17T19:39:37.227 回答