您的位置:首页 > Web前端 > JQuery

jQuery、PHP上传图片

2016-03-07 17:02 706 查看
通过jQuery上传图片,PHP对上传图片处理后保存到服务器指定目录下。可以页面部分刷新,提升了用户体验。

<!--picuploadHtml.php,上传图片表单-->
<html>
<head>
<title>Picture Upload</title>
</head>
<script src="<span style="font-family:Consolas, Bitstream Vera Sans Mono, Courier New, Courier, monospace;color:#0000ff;"><span style="font-size: 13.3333px; line-height: 14.6667px;">http://code.jquery.com/jquery-latest.js</span></span>" type="text/javascript"></script>
<body>
<form id="uploadForm">
<tr>
<td>图片上传:</td>
<td>
<input type="text" id="picUrl" name="picUrl" size="50%">
<br />
<button id="picUpload" type="button">上传图片</button>
<div id='uploadLog'></div>
<br />
<img style="width: 500px; height: 200px;" src="" id="thumbImg" alt="缩略图" />
</td>
</tr>
</form>

<form id='formFile' name='formFile' method="post" action="picuploadPHP.php" target='iframeFile' enctype="multipart/form-data">
<input type='file' id='img' name='img' style="display: none;"/>
</form>

<iframe id='iframeFile' name='iframeFile' style='display: none;'></iframe>

<script>
$(function() {
$('#picUpload').click(function(){//按钮被点击
$('#img').click();
});

$('#img').change(function() {
$('#uploadLog').html('开始上传中....');
$('#formFile').submit();
});
})
function uploadCallback(ret) {
var ret = JSON.parse(ret);//注意JSON.parse中的转义字符(\)
//http://www.jb51.net/article/39828.htm
if(ret.error_no == 0){
alert('图片上传成功!');
$('#uploadLog').html('');
$('#thumbImg').attr('src', ret.browserUrl);
$('#picUrl').val(ret.serverUrl);
}else{
$('#uploadLog').html('');
alert(ret.error_info);
}
}
</script>

</body>
</html>

<?php
//picuploadPHP.php,图片接收PHP程序
$pathinfo = pathinfo($_FILES['img']['name']);
$extension = $pathinfo['extension'];//取得上传文件后缀名

$allow_ext = array('jpeg', 'png', 'gif', 'jpg');
if (!in_array($extension, $allow_ext)) {
$arr = array('error_no' => '-1', 'error_info' => '文件格式不允许!');
uploadCallback($arr);
}

if ($_FILES['img']['size'] > 200000) {//200000字节(200kb)
$arr = array('error_no' => '-1', 'error_info' => '文件超出大小限制!');
uploadCallback($arr);
}

if ($_FILES['img']['error'] != 0) {
$arr = array('error_no' => '-1', 'error_info' => '图片上传失败!');
uploadCallback($arr);
}

$filepath = 'D:\\\\\\\\XAMPP\\\\htdocs\\\\picUpload\\\\images\\\\uploadPic.'.$extension;
$browserPath = 'http://localhost/picUpload/images/uploadPic.'.$extension;
$res = move_uploaded_file($_FILES['img']['tmp_name'], $filepath);//只能移动POST上传的文件
if ($res) {
$arr = array('error_no' => '0', 'serverUrl' => $filepath, 'browserUrl' => $browserPath);
uploadCallback($arr);
} else {
$arr = array('error_no' => '-1', 'error_info' => '图片保存失败!');
uploadCallback($arr);
}

function uploadCallback($arr)
{
$json = json_encode($arr);
echo "<script>parent.uploadCallback('$json')</script>";
exit;
}

?>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息