工作中总会有需要自己写前端上传图片功能,特意保留一下自己感觉还好的前端上传图片代码
主要介绍了PHP上传图片显示缩略图功能代码,

前端html代码

<input type="hidden" name="pic" id="slide_img"  value="" data-style="height:84px;">
<a href="javascript:;" id="upload_box" class="addUpload"  onclick="addImage('#slide_img')" ><img width="84px;" src="/refund/img/upload.png"/>
</a>
<!--上传图片使用的form和显示样式-->
<script src="<{:C('CSSJSHOST')}>/wap/assets/js/upload_img/upload_img.js"></script>
<form name="form1" method="post" action="/my/upload_img_callback.html" target="imageUpload"enctype="multipart/form-data" style="display:none;"><input type="file" name="imageFile" id="imageFile"  accept="image/*" onchange="uploadFile(this)"><input type="hidden" name="imageTag" id="imageTag">
</form>
<iframe id="imageUpload" name="imageUpload" src="about:blank" style="display:none"></iframe>
<div class="uploadBackdrop"></div>
<div class="mwrap" id="uploadPopup" style="display:none"><div class="inner"><div class="spinner"><div class="rect1"></div><div class="rect2"></div><div class="rect3"></div><div class="rect4"></div><div class="rect5"></div></div><p>正在上传</p></div>
</div>
<!---->

addImage() 函数是上传图片事件,里面的参数是input 标签,到时候图片上传完之后要把值赋值到改input标签

JS 代码


/*** 添加图片点击* @param id*/
function addImage(id) {$('#imageFile').attr('container', id).click();$('#imageTag').val(id);
}
/*** 添加图片点击* @param id*/
function addImageChapter(id,book_id) {$('#imageFile').attr('container', id).click();$('#imageTag').val(id+'_'+book_id);
}
/*** 更换图片点击* @param el*/
function changeImage(el) {if (confirm('你是要换一张么?')) {$(el).siblings(".hidden").val('');$(el).siblings(".addUpload").show();$(el).remove();}
}/*** 上传文件* @param input*/
function uploadFile(input) {if (input.files.length > 0) {var form1 = document.form1;form1.submit();startUploadPopup();}input.value = null;
}/*** 上传成功* @param data*/
function uploadSuccess(data) {closeUploadPopup();// $('.addUpload').hide();var container = $('#imageFile').attr('container');console.log(container)if (container == '.pics') {$(container).append('<li class="img_node"><input name="chapter_imgs[]" type="hidden" value="' + data + '"><img src="' + data + '" alt=""><span class="close" οnclick="closePic(this)"></span><span class="close left" οnclick="leftPic(this)"></span><span class="close right" οnclick="rightPic(this)"></span></li>');} else {$('#slide_img').hide();$(container).hide();$(container).siblings(".addUpload").hide();$(container).val(data);$(container).parent().append('<a href="javascript:void(0);" class="uploadPics" οnclick="changeImage(this)"><img src="' + data + '" style="'+$(container).data('style')+'"></a>');}
}function substrUrl(url) {var index = url.indexOf('http://img.ai7.com/');if (index != -1) {return url.substring(index + 19);} else {return url;}
}
function uploadError(data) {closeUploadPopup();alert(data);
}
function startUploadPopup() {$("#uploadPopup p").text('正在上传');$("#uploadPopup,.uploadBackdrop").show();
}
function closeUploadPopup() {$("#uploadPopup,.uploadBackdrop").hide();
}
function closePic(el) {$(el).parent().remove()
}
function leftPic(el) {if($(el).parent().prev().hasClass('img_node'))$(el).parent().insertBefore($(el).parent().prev());
}
function rightPic(el) {if($(el).parent().next().hasClass('img_node'))$(el).parent().insertAfter($(el).parent().next());
}

PHP代码

/*** 上传图片* @return mixed*/function upload_img_callback()
{header('Content-Type: application/javascript; charset=utf-8;');$imgTag = input('imageTag');$subPath = 'default';if ($imgTag == '#thumb') {$subPath = 'book';} elseif ($imgTag == '#slide_img') {$subPath = 'slide';} elseif ($imgTag == '#active_img') {$subPath = 'active';}$info = uploadImg('imageFile', $subPath);if ($info['status'] == 1) {echo "<script>parent.uploadSuccess('" . $info['msg'] . "')</script>";} else {echo "<script>parent.uploadError('" . $info['msg'] . "')</script>";}
}// 生成文件路径
function mkDirs($path)
{$array_path = explode("/", $path);$_path = "";for ($i = 0; $i < count($array_path); $i++) {$_path .= $array_path[$i] . "/";if (!empty($array_path[$i]) && !file_exists($_path)) {mkdir($_path, 0777);}}return true;
}/*** 上传图片*/
function uploadImg($input = 'image', $subPath = 'default')
{$upload_dir = dirname(dirname(dirname(__DIR__))) . '/';$picnowurl = "图片域名"; // 图片域名$file = $_FILES[$input];if ($file == null) {return array('status' => -1, 'msg' => '上传文件不存在');}$name = $file["name"];// 文件名$type = $file["type"];// 文件类型$size = $file["size"];// 文件大小$tmp_name = $file['tmp_name'];$error = $file["error"];/上传的图片浏览器的类型不同,$type的值也不同if (!in_array($type, array('image/pjpeg', 'image/jpeg', 'image/gif', 'image/x-png','image/png'))) {return array('status' => -1, 'msg' => '不支持的图片文件类型');}上传文件路径$time = date("YmdHis");$picture_name = strstr($name, "."); //通过strstr()函数截取上传图片的后缀$picallname = $subPath . $time . rand(1000, 9999);$diryearmonth = date("Ym");$dirday = date("d");$savePath = $upload_dir . "/uploads/" . $subPath . "/" . $diryearmonth . "/" . $dirday . "";$fileupname = "/uploads/" . $subPath . "/" . $diryearmonth . "/" . $dirday . "/" . $picallname . $picture_name;if ($error == '0') {// 上传到当前服务器
//        $this->mkDirs($savePath);
//        move_uploaded_file($tmp_name, $upload_dir . $fileupname); // //上传图片的函数()$res = $this->imgToBase64($tmp_name, $subPath); // 使用base64上传到远程return array('status' => 1, 'msg' => $res);}return array('status' => 1, 'msg' => $picnowurl . $fileupname);
}/*** 获取图片的Base64编码(不支持url)* @date 2017-02-20 19:41:22* @param string $img_file 传入本地图片地址* @param string $subPath 存储图片路径* @return string*/
function imgToBase64($img_file='', $subPath='')
{$img_url = '';if (file_exists($img_file)) {$img_info = getimagesize($img_file); // 取得图片的大小,类型等$content = file_get_contents($img_file);if ($content) {$file_content = chunk_split(base64_encode($content)); // base64编码switch ($img_info[2]) {           //判读图片类型case 1:$img_type = "gif";break;case 2:$img_type = "jpg";break;case 3:$img_type = "png";break;case 6:$img_type = "bmp";break;default:return false;}$img_base64 = 'data:image/' . $img_type . ';base64,' . $file_content;//合成图片的base64编码$post_data = array('type' => $subPath,'file' => $img_base64,);$url = '/lm_upload_thumb.php';// 远程上传图片地址(base64上传文件)$res = json_decode(http_post($url, $post_data), true);if ($res['rtn'] == 1) {unlink($img_file);}$img_url = $res['data'];}}return $img_url; //返回图片的base64
}

lm_upload_thumb.php文件 -

base64上传图片方法


$subPath = ($_POST['type']);
$base64_image_content = $_POST['file'];$back_data = array('rtn'=>0,'data'=>'','msg'=>'no',
);if (empty($base64_image_content) || !$subPath) { echo json_encode($back_data);exit();
}
$document_root = dirname(__DIR__).'/app.com';
$path = local_path($subPath);
$path = trim($path, "/");
if (!file_exists($document_root . "/" . $path)){mkdir ($document_root . "/" . $path,0777,true);
}$time = time();
// 将格式为base64的字符串解码
preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_image_content, $result);
$img_type = $result[2];
$picallname=$subPath.$time.rand(1000,9999);
$filename =  $picallname. ".{$img_type}"; $url_path = 'https://p.***.cn/' . $path . "/" . $filename;
if (!file_exists($document_root . "/" . $path."/".$filename)){   file_put_contents($document_root . "/" . $path."/".$filename, base64_decode(str_replace($result[1], '', $base64_image_content)));
}$back_data['data'] = $url_path;
$back_data['rtn'] = 1;
echo json_encode($back_data);
exit(); function local_path($subPath)
{$diryearmonth=date("Ym");$dirday=date("d");$path = "/uploads/lmcps/".$subPath."/".$diryearmonth."/".$dirday."";if (file_exists($path) === false) {mkdir('.' . $path, 0777, true);chmod('.' . $path, 0777);}return $path;
}

php图片上传功能,实时显示上传的图片相关推荐

  1. Office文档上传后实时转换为PDF格式_图片文件上传后实时裁剪_实现在线预览Office文档

    Office文档上传后实时转换为PDF格式_图片文件上传后实时裁剪 前置条件 安装LibreOffice 安装OpenOffice 安装Unoconv 安装ImageMagick.x86_64 安装G ...

  2. 上传文件实时显示网速怎么实现_担心PC程序吃内存占网速?有了它终于放心了...

    自乔帮主发布iPhone至今,智能手机已经走过了13个年头,其系统.UI.操作逻辑都已经逐步完善且相当傻瓜化. 所以总有许多人切换到PC上时,总感觉缺了那么点东西,Windows系统的生产力自然是毋庸 ...

  3. asp.net中使用Uploadify插件实现多张图片上传,上传后可显示缩略图、删除图片

    本文为原创文章,欢迎转载!转载时请注明出处:http://blog.csdn.net/c_yang13 一.准备工具 1.jquery,我使用的是jquery-1.11.3.min.js 2.uplo ...

  4. 利用鼠标在图像上画框并实时显示鼠标所点击处坐标

    我们在做小型项目的时候,有时为了实现良好的交互,或者更方便实时观察输入数据,通常需要使用到下列几项功能: 1.利用鼠标在所显示的图像/视频中选取ROI区域 2.实时显示鼠标所点击位置处的坐标信息 本文 ...

  5. vue获取上传进度_vue,webuploader实现文件分片上传,并显示上传进度

    1.效果图 2.上传文件时,如果使用普通上传,则需要上传一个文件完成后才能上传下一个文件,如果文件很大时,可能会造成浏览器无响应,如果采用分片上传方式,将一个大文件分割成多块,并发上传,极大地提高大文 ...

  6. 使用compressorjs压缩图片,优化功能,压缩所有格式的图片

    上一篇文章写的图片压缩功能只适用于image/jpeg和image/webp图像.vue实现图片压缩,支持多文件上传时压缩图片(只能支持jpeg)_ZMJ_QQ的博客-CSDN博客 在实际开发中常见的 ...

  7. word中图片为嵌入式格式时显示不全_word中图片设置嵌入式后无法显示完整的解决方案(转)...

    word中图片的格式和文字段落的格式有这很密切的联系 在使用word 中,您要记住一点,如果您要使得您插入的图片样式为嵌入式,那么在文字的段落设置中选哪个行距都可以,但惟独不能选择固定行距,下面分别演 ...

  8. word中图片为嵌入式格式时显示不全_word嵌入图片显示不全怎么办-word嵌入图片显示不全的解决方法 - 河东软件园...

    word是我们最常用的办公组件之一,其具备了强大的文字编辑与文字处理功能,帮助用户轻松的进行编辑,而在使用word的过程中,我们难免需要在其中插入图片,从而帮助我们更好的表达我们的内容,而部分用户在插 ...

  9. php验证码显示碎图片,我的验证码只显示破碎的小图片

    源自:2-1 验证码制作 我的验证码只显示破碎的小图片 header("content-type:image/gif"); //通过GD库做验证码 //创建画布 session_s ...

  10. word中图片为嵌入式格式时显示不全_word嵌入图片显示不全-不同类型文档中图片设置的几个小技巧...

    在办公中,我们时常需要编辑文档,特别是有图片的文档涉及到一些格式处理,所以掌握一些编辑文档的技巧是提高工作效率必备的.以下是关于Word和PDF文档插入图片后的一些设置,一起来看看吧! 一.Word文 ...

最新文章

  1. [转载]交换机背板带宽计算方法
  2. Django的Form表单
  3. 【知识星球】ElementAI提出超复杂多尺度细粒度图像分类Attention模型
  4. 八、“看夕阳西下,烂漫秋霞”
  5. Hibernate(十):n-n关联关系
  6. Aladdin and the Flying Carpet (素数打表+正整数的唯一分解定理,找因数对)
  7. WebAPI PUT,DELETE请求404
  8. Linux(centos7.4)上FTP服务器搭建(使用yum)
  9. zabbix企业应用之固定端口监控memcache
  10. 第九周-每周例行报告
  11. c语言程序设计黄保和第二章,c语言程序设计答案(选择题+编程)黄保和、江戈版...
  12. 计算机职称考试试题 操作题,2018职称计算机考试Excel备考试题及答案9-excel操作练习题...
  13. HP.Infotech.CodeVisionAVR.v1.24.6.Pro
  14. 微信脚本配置服务器,微信自动加人脚本教程
  15. Chibi Dinos上线薄饼IFO打新,是否值得参与?
  16. 精密测量和超精密测量
  17. 阿拉丁2022 年度小程序白皮书发布,8 亿 DAU 再现小程序繁荣生态
  18. 【php】PHP数据库访问
  19. C++--数值的整数次方
  20. 华为鸿蒙和美的,美的与华为鸿蒙合作,为智能家居领域带来更深度的场景与服务...

热门文章

  1. 从零开始配置腾讯云 CDN的设置教学
  2. python做相册_Python编程:制作电子相册
  3. python做相册_《自拍教程73》Python 自动生成相册文件夹
  4. java分页查询参数封装
  5. 最佳阵容问题matlab,数学建模-最佳阵容问题.doc
  6. 追加审批人样式html,更新 | 你的审批打印模板真丑!看别人用html模板怎么玩
  7. python生存曲线_用户行为与生存分析
  8. 编码、学习、玩耍一条龙,这是我看过最良心的「游戏编程」网站,没有之一!...
  9. html 做填写的表格,CSS写的简单表格示例
  10. 使用Layui制作的简单数据表格