如何运用PHP Ajax实现图片的无刷新上传
1个回答
展开全部
<meta charset="utf-8" >
<form id= "uploadForm">
<p >指定文件名: <input type="text" name="filename" value= ""/></p >
<p>
上传文件:
<input type="file" name="photo" onchange="showPreview(this)" class="file" />
<img id="portrait" src="" width="70" height="75">
</p>
<input type="button" value="上传" onclick="doUpload()" />
</form>
<script src="http://www.haoyunyun.cn/jquery.js"></script>
<script>
function doUpload() {
var formData = new FormData($( "#uploadForm" )[0]);
$.ajax({
url: 'submit.php' ,
type: 'POST',
data: formData,
async: false,
cache: false,
contentType: false,
processData: false,
success: function (returndata) {
alert(returndata);
},
error: function (returndata) {
alert(returndata);
}
});
}
</script>
<script type="text/javascript">
function showPreview(source) {
var file = source.files[0];
if (window.FileReader) {
var fr = new FileReader();
fr.onloadend = function(e) {
document.getElementById("portrait").src = e.target.result;
};
fr.readAsDataURL(file);
}
}
</script>
<?php
if($_FILES['photo']['error']>0){
echo "上传文件失败";
die;
}
$dir='./photo/';
$type=substr($_FILES['photo']['name'],strrpos($_FILES['photo']['name'],'.'));
$filename=time().rand(1000,9999).$type;
if(is_uploaded_file($_FILES['photo']['tmp_name'])){
move_uploaded_file($_FILES['photo']['tmp_name'],$dir.$filename);
echo "上传成功";
}else{
echo "上传文件失败";
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询