上传图片到php服务器
生活随笔
收集整理的這篇文章主要介紹了
上传图片到php服务器
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
html代碼
<!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><title>上傳圖片到服務器</title><script src="lib/jquery-1.8.3.min.js"></script><style>#box2 {width: 100px;height: 100px;background-color: aquamarine;position: absolute;}#box{height:200px;width:440px;border:2px solid red;}</style> </head> <body><div class="container"><input id="imagefile" type="file" name="filename" /><!-- ondragenter="drager()" --><img id="preview" alt="image" style="height: 200px;" name="pic" ondragover="allowDrop(event)" ondrop="drop1(event)"/></div><div id="box2"></div><script>function allowDrop(ev){ev.preventDefault();}var oDiv = document.getElementById("box2");oDiv.onmousedown=function(ev){var oEvent = ev; var disX = oEvent.clientX - oDiv.offsetLeft;//offsetLeft,offsetTop:相對于最近的祖先定位元素。var disY = oEvent.clientY - oDiv.offsetTop;document.onmousemove=function (ev){oEvent = ev;oDiv.style.left = oEvent.clientX -disX+"px";oDiv.style.top = oEvent.clientY -disY+"px";}document.onmouseup=function(){document.onmousemove=null;document.onmouseup=null;} }//點擊input標簽添加$("#imagefile").change(function() { if(typeof FileReader == 'undefined') {alert("抱歉,你的瀏覽器不支持FileReader,無法圖片上傳"); } var file = this.files[0]; postImg(file);});// 拖拽添加function drop1(ev){ev.preventDefault(); var fileList = ev.dataTransfer.files; //獲取文件對象if(fileList.length == 0){return false;}if(fileList[0].type.indexOf('image') === -1){alert('您拖的不是圖片!')return false;}postImg(fileList[0]);};// 封裝上傳function postImg(file){var reader = new FileReader(); reader.readAsDataURL(file); //dataurl的格式為data:image/******;adshgflkasnga,意思是文件頭+二進制串,可用;分割reader.onload = function(e) { $.post("./img.php",{ img: e.target.result }, //post成功后的回調函數function(ret) { if(ret.img != '') {var pic = document.getElementById("preview");pic.src = ret.img; } else { alert('upload fail'); }},'json');}}</script> </body> </html>php代碼
$img1 = $_POST['img'];$img = $img1?$img1:'';list($type,$data) = explode(',',$img);if(strstr($type,'image/jpeg')!==''){$ext = ".jpg";}elseif(strstr($type,'image/gif')!==''){$ext = ".gif";}elseif(strstr($type,'image/png')!==''){$ext = ".png";}$photo = time().$ext;$photo_path = "img/{$photo}";file_put_contents($photo_path,base64_decode($data),true);header('content-type:application/json;charset=utf-8');$ret = array('img'=>$photo_path);echo json_encode($ret);總結
以上是生活随笔為你收集整理的上传图片到php服务器的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 51cto的请看过来
- 下一篇: rsa/ecb/pkcs1padding