继续上代码:
index.html:
<html> <head> <meta charset="UTF-8"> <title></title> <script type="text/javascript"> function getFileUrl(sourceId) { var url; if (navigator.userAgent.indexOf("MSIE")>=1) { // IE url = document.getElementById(sourceId).value; } else if(navigator.userAgent.indexOf("Firefox")>0) { // Firefox url = window.URL.createObjectURL(document.getElementById(sourceId).files.item(0)); } else if(navigator.userAgent.indexOf("Chrome")>0) { // Chrome url = window.URL.createObjectURL(document.getElementById(sourceId).files.item(0)); } return url; } function convertImgToBase64(url, callback, outputFormat){ var canvas = document.createElement('CANVAS'), ctx = canvas.getContext('2d'), img = new Image; img.crossOrigin = 'Anonymous'; img.onload = function(){ canvas.height = img.height; canvas.width = img.width; ctx.drawImage(img,0,0); var dataURL = canvas.toDataURL(outputFormat || 'image/png'); callback.call(this, dataURL); canvas = null; }; img.src = url; } /* convertImgToBase64('http://bit.ly/18g0VNp', function(base64Img){ // Base64DataURL }); */ </script> </head> <body> <form name="myfrom" id="myform" action="saveimg.php" method="post"> <img width="100" height="100" id="myimg"> <input type="file" id="myfile" > <input type="hidden" name="myhidden" id="myhidden"> <input type="button" id="st" value="提交"> </form> <script type="text/javascript"> (function() { document.querySelector("#myfile").onchange = function(){ console.log(this.value); document.querySelector("#myimg").src = getFileUrl(this.id); }; document.querySelector("#st").onclick = function(){ var fsrc; fsrc = getFileUrl("myfile"); convertImgToBase64(fsrc, function(base64Img){ console.log('11111111111111111'); //console.log(base64Img); // Base64DataURL document.querySelector("#myhidden").value = base64Img; document.querySelector("#myform").submit(); }); }; } )(); </script> </body> </html> 上面代码中现在看来没什么难点,有疑问请看我上一篇文章 js本地预览图片和转base64接下来我们开始创建php文件
saveimg.php:<html> <head> <meta charset="UTF-8"> <title></title> <script type="text/javascript"> </script> </head> <body> <? $img = $_POST['myhidden']; //匹配出图片的格式 if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $img, $result)){ $type = $result[2]; $new_file = "./tesstimg/"; if(!file_exists($new_file)) { //检查是否有该文件夹,如果没有就创建,并给予最高权限 mkdir($new_file, 0700); } $new_file = $new_file.time().".{$type}"; if (file_put_contents($new_file, base64_decode(str_replace($result[1], '', $img)))){ echo '新文件保存成功:', $new_file; }else{ echo '新文件保存失败'; } } ?> <img src="<?=$img?>"> </body> </html>