PHP上传图片

本文介绍了一个使用HTML、JavaScript和PHP实现的图片上传功能,包括前端的文件选择、图片预览,以及后端的图片接收与存储过程。通过FileReader API读取文件并转化为Data URL,再使用Ajax发送至服务器,最后在页面上显示上传成功的图片。
HTML部分:
<
div class="sc-img"></div> <p><input type="file" class="file" id="img"></p>
javascript部份:
$('#img').change(function(){ var img = event.target.files[0]; // 判断是否图片 if(!img){ return ; } // 判断图片格式 if(!(img.type.indexOf('image')==0 && img.type && /\.(?:jpeg|jpg|png|gif)$/.test(img.name)) ){ alert('图片只能是jpeg,jpg,gif,png'); return ; } var reader = new FileReader(); reader.readAsDataURL(img); reader.onload = function(e){ $.ajax({ url: "scImg.php", method: 'POST', data: { img:e.target.result}, success: function(msg) { // alert('上传成功'); $('.sc-img').html('<img style='+'height:100%;'+' src="' + msg.img + '">'); console.log('src',msg.img); },error:function(){ console.log('上传失败'); } }); } });
php部分:scImg.php
<?php $path="uppic/"; if(!file_exists($path)) { mkdir("$path", 0777); } $img = isset($_POST['img'])? $_POST['img'] : ''; // 获取图片 list($type, $data) = explode(',', $img); // 判断类型 if(strstr($type,'image/jpeg')!=''){ $ext = '.jpeg'; }elseif(strstr($type,'image/gif')!=''){ $ext = '.gif'; }elseif(strstr($type,'image/png')!=''){ $ext = '.png'; }elseif(strstr($type,'image/jpg')!=''){ $ext = '.jpg'; } // 生成的文件名 $photo = time().$ext; // 生成文件 file_put_contents($path."/".$photo, base64_decode($data), true); // 返回 header('content-type:application/json;charset=utf-8'); $ret = array('img'=>$path.$photo); echo json_encode($ret); ?>

 

转载于:https://www.cnblogs.com/beli/p/7462487.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值