functiongetFileUrl(sourceId) {
varurl;
if(navigator.userAgent.indexOf("MSIE")>=1) { // IEurl= document.getElementById(sourceId).value;
} else if(navigator.userAgent.indexOf("Firefox")>0) { // Firefoxurl= window.URL.createObjectURL(document.getElementById(sourceId).files.item(0));
} else if(navigator.userAgent.indexOf("Chrome")>0) { // Chromeurl= window.URL.createObjectURL(document.getElementById(sourceId).files.item(0));
}
returnurl;
}
functionconvertImgToBase64(url, callback, outputFormat){
varcanvas= document.createElement('CANVAS'),
ctx= canvas.getContext('2d'),
img= newImage;
img.crossOrigin = 'Anonymous';
img.onload = function(){
canvas.height= img.height;
canvas.width= img.width;
ctx.drawImage(img,0,0);
vardataURL= canvas.toDataURL(outputFormat || 'image/png');
callback.call(this, dataURL);
canvas= null;
};
img.src = url;
}
/*convertImgToBase64('http://bit.ly/18g0VNp', function(base64Img){// Base64DataURL});*/
(function() {
document.querySelector("#myfile").οnchange= function(){
console.log(this.value);
document.querySelector("#myimg").src= getFileUrl(this.id);
};
document.querySelector("#st").οnclick= function(){
varfsrc;
fsrc= getFileUrl("myfile");
convertImgToBase64(fsrc, function(base64Img){
console.log('11111111111111111');
//console.log(base64Img);// Base64DataURLdocument.querySelector("#myhidden").value= base64Img;
document.querySelector("#myform").submit();
});
};
}
)();
上面代码中现在看来没什么难点,有疑问请看我上一篇文章 js本地预览图片和转base64接下来我们开始创建php文件
saveimg.php:
$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 '新文件保存失败';
}
}
?>