h5+php实现图片上传
html:
<form enctype="multipart/form-data" method="post">
<input type="file" id="uploadFile" runat="server" />
<input type="button" id="btnUpload" value="确定" onclick="uploadImage()" />
<div id="imgDiv">
</div>
</form>
<script type="text/javascript">
function uploadImage() {
//判断是否有选择上传文件
var imgPath = $("#uploadFile").val();
if (imgPath == "") {
alert("请选择上传图片!");
return;
}
//判断上传文件的后缀名
var strExtension = imgPath.substr(imgPath.lastIndexOf('.') + 1);
if (strExtension != 'jpg' && strExtension != 'gif'
&& strExtension != 'png' && strExtension != 'bmp') {
alert("请选择图片文件");
return;
};
var formdata = new FormData();
var fileObj = $("#uploadFile").get(0).files;
formdata.append("file", fileObj[0]);
formdata.append("aid", 30);
formdata.append("nickname", "你好");
$.ajax({
type: "POST",
url: 'test.php',
data: formdata,
processData: false,
contentType: false,
cache: false,
success: function(data) {
//alert("上传成功");
$("#imgDiv").empty();
$("#imgDiv").html(data);
$("#imgDiv").show();
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
//alert("上传失败,请检查网络后重试");
console.log(XMLHttpRequest);
console.log(textStatus);
console.log(errorThrown);
}
});
}
</script>
test.php:
<?php
//如果接收的数据包含图片文件
if(isset($_FILES['file'])){
$aid = intval($_POST['aid']);
$nickname = ($_POST['nickname']);
//获取图片的临时路径
$image = $_FILES["file"]['tmp_name'];
//只读方式打开图片文件
$fp = fopen($image, "r");
//读取文件(可安全用于二进制文件)
$file = fread($fp, $_FILES["file"]["size"]); //二进制数据流
//保存地址
$imgDir = 'account_imgs/';
//要生成的图片名字
//$filename = date("Ym")."/".md5(time().mt_rand(10, 99)).".jpg"; //新图片名称
$filename = "2017new.jpg";
//新图片的路径
$newFilePath = $imgDir.$filename;
$data = $file;
$newFile = fopen($newFilePath,"w"); //打开文件准备写入
fwrite($newFile,$data); //写入二进制流到文件
fclose($newFile); //关闭文件
//写入数据库
$sql = "update account set nickname = '".$nickname."', img = '".$filename."' where aid = ".$aid;
if(!$db->query($sql)) {
Json_out(array('result'=>'imgfail'));
exit;
}else{
Json_out(array('result'=>'imgsuccess'));
exit;
}
} else{
$aid = intval($_REQUEST['aid']);
$nickname = $_REQUEST['nickname'];
$sql = "update `account` set nickname = '".$nickname."' where aid = ".$aid;
if(!$db->query($sql)) {
Json_out(array('result'=>'fail'));
exit;
}else{
Json_out(array('result'=>'noimgsuccess'));
exit;
}
}
?>