<html>
<div class="upload_list">
<div class="upload_text size_15px color_gray text_left">上传截图</div>
<input type="file" onchange="upImage(this)" style="visibility: hidden;position: absolute" id="img" name="imgFile">
<input id="hidden_img" type="hidden" name="img">
<div class="upload_imges">
<div class="upload">
<div class="upload_imges_list">
</div>
</div>
</div>
</div>
</html>
<script>
function upImage (obj){
run(obj, function (data) {
var src = window.URL.createObjectURL(obj.files[0]);
var str = '<img class="upload_img" id="show_img" src="'+data+'"/>';
$('.upload_imges_list').append(str);
$("#hidden_img").val(data);
});
}
function run(input_file,get_data){
/*input_file:文件按钮对象*/
/*get_data: 转换成功后执行的方法*/
if ( typeof(FileReader) === 'undefined' ){
alert("抱歉,你的浏览器不支持 FileReader,不能将图片转换为Base64,请使用现代浏览器操作!");
} else {
try{
/*图片转Base64 核心代码*/
var file = input_file.files[0];
//这里我们判断下类型如果不是图片就返回 去掉就可以上传任意文件
if(!/image\/\w+/.test(file.type)){
alert("请确保文件为图像类型");
return false;
}
var reader = new FileReader();
reader.onload = function(){
get_data(this.result);
}
reader.readAsDataURL(file);
}catch (e){
alert('图片上传出错啦!'+ e.toString())
}
}
}
</script>
<?php
$path = 'uploads/report';
if($post['img']){
if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $post['img'], $result)){
$new_file = $path."/".date('Ymd',time())."/";
if(!file_exists($new_file)){
mkdir(iconv("UTF-8", "GBK", $new_file),0777,true);
}
$new_file = $new_file."report_".rand(1000000,9999999).$member_info['member_id'].".jpg";
if (file_put_contents($new_file, base64_decode(str_replace($result[1], '', $post['img'])))){
$img = 'http://'.$_SERVER['HTTP_HOST'].'/'.$new_file;
$model->img =$img;
}
}
}
php 图片上传(base64方式)
最新推荐文章于 2024-07-15 11:11:31 发布