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