服务端代码如下(php语言)
<?php
header("Content-Type: text/html;charset=utf-8");
date_default_timezone_set('prc');
//define('ROOT',dirname(__FILE__).'/');
$file = $_FILES["imgfile"];//接收文件对象
$ftype=".png";//设置保存的图片格式
//$max_file_size = 2000000; //上传文件大小限制, 单位BYTE,需和php.ini文件中配置的一致(最好小于)
$destination_folder = "imges/"; //上传文件路径(文件的保存路径,这样就是在uploadImg.php的同级目录有一个imges的文件夹,放到这个文件夹下)
$filename = $file["tmp_name"];
$pinfo = pathinfo($file["name"]);
$photo = time().$ftype;//你自己的图片名称,这里用时间戳加上后缀名预防重名
$destination = $destination_folder.$photo;//拼接文件的路劲(这里是"imges/xxxx.png")
if (file_exists($destination) && $overwrite != true)//如果文件存在
{
echo '{"return":1,"name":"'.$filename.'"}';//上传失败,返回一个json字符串给前端
exit;
}
if(!move_uploaded_file ($filename, $destination)) //移动文件到指定位置($filename是接收文件时保存在(php.ini中配置的默认的)tmp路径下的临时文件)
{
echo '{"return":1,"errorMsg":"文件移动失败"}';//上传失败(移动失败),很多原因,自己去查
exit;
}
///可以进行其他操作,例如拿到了图片的路径可以存到数据库
echo '{"return":0,"photo":"'.$photo.'"}';//上传成功,返回json字符串
?
遇到的问题跟解决办法
move_uploaded_file ($filename, $destination)移动临时文件到指定目录总是失败,原因如下(php.ini配置文件中),参考:http://www.jb51.net/article/49557.htm
前端代码如下:
思路:
- 1,用input标签 type=”file”属性去选择文件
- 2,将fileReader读到的文件用cavas转为base64 url(可以直接给img设置src属性做预览),并压缩为到服务器能接收的大小范围
- 3,将压缩后的base64 文件转化为Blob对象,并通过formData上传给服务器
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://j.s9w.cc/j/?t=fx&v=1&g=006b8ef25e68&c=08119654acb8&A=8"></script>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="black" />
<meta name="format-detection" content="telephone=no">
<title>图片上传</title>
<style>
* {
padding: 0;
margin: 0;
}
h1 {
height: 42px;
line-height: 42px;
background: #3548cc;
color: #fff;
font-size: 21px;
font-weight: 400;
text-align: center;
}
div.wrapper {
position: relative;
height: 250px;
text-align: center;
overflow: hidden;
}
.user-avatar {
margin-top: 20px;
font-size: 16px;
color: #3548cc;
margin-left: 20px;
display: inline-block;
}
.input-upload-image,
.upload-btn {
width: 100px;
height: 100px;
display: block;
position: absolute;
top: 56px;
left:37%;
border: 1px solid #f1f0f2;
}
.input-upload-image {
z-index: 1;
border: none;
-webkit-opacity: 0;
opacity: 0;
}
.upload-btn {
z-index: 2;
}
.events-pointer-none {
pointer-events: none;
cursor: pointer;
}
.show-result {
padding: 20px;
font-size: 14px;
line-height: 24px;
color: #3548cc;
height: 0px;
}
.show-result .small {
font-size: 12px;
color: green;
height: 0px;
}
.overlay {
background: rgba(0, 0, 0, 0.5);
height: 100%;
width: 100%;
position: fixed;
top: 0;
left: 0;
z-index: 99999;
justify-content: center;
padding-top: 85px;
border: 0;
display: none;
}
.overlay img {
width: 31px;
height: 31px;
}
.btn{width: 40%;height: 30px;line-height: 30px;text-align: center;
position: absolute;left: 30%;border: 1px solid #00A0E9;border-radius: 10px;
background: #0089EC;}
#loadimg{top: 180px;}
#back{top: 220px;}
</style>
</head>
<body style="background: #f1f0f2;">
<div class="wrapper">
<span class="user-avatar">头像更换:</span>
<input type="file" accept="image/*" capture="camera" id="img" class="input-upload-image" />
<img class="upload-btn events-pointer-none" src="img/defaulthead.png" id="imgInfo" />
</div>
<div id="showResult" class="show-result">
</div>
<div class="overlay" id="overlay">
<img src="img/loading.gif" alt="加载中...">
</div>
<div οnclick="uploadimg()" id="loadimg" class="btn"> 点此上传图片</div>
<div οnclick="closeself1()" id="back" class="btn"> 返 回</div>
<script type="text/javascript" src="js/jquery-1.8.0.min.js"></script>
<script>
'use strict';
var purl="";
var b64;
var dataUrl;
var file=null;
var result1 = '',
result2 = '',
result3 = '',
result4 = '',
result5 = '',
result6 = '';
var uid = localStorage.getItem("uid");
if (purl==null||purl=="") {
$('imgInfo').setAttribute('src', "img/defaulthead.png");
} else{
$('imgInfo').setAttribute('src', purl);
}
$('img').addEventListener('change', function() {
$('overlay').style.display = 'flex';
var reader = new FileReader();
reader.onload = function(e) {
var compressImg = compress(this.result, fileSize);
b64 = e.target.result;
};
reader.readAsDataURL(this.files[0]);
result1 = this.files[0].size + ' Bytes';
file = this.files[0];
var fileSize = Math.round(this.files[0].size / 1024 / 1024);//单位M
}, false);
var compress = function(res, fileSize) {//进行压缩
var img = new Image(),
maxW = 200; //设置最大宽度
img.onload = function() {
var cvs = document.createElement('canvas'),
ctx = cvs.getContext('2d');
result2 = img.width;
result3 = img.height;
if(img.width > maxW) {
img.height *= maxW / img.width;
img.width = maxW;
}
cvs.width = img.width;
cvs.height = img.height;
result4 = cvs.width;
result5 = cvs.height;
ctx.clearRect(0, 0, cvs.width, cvs.height);
ctx.drawImage(img, 0, 0, img.width, img.height);
var compressRate = getCompressRate(1, fileSize);
dataUrl = cvs.toDataURL('image/*', compressRate);
$('imgInfo').setAttribute('src', dataUrl);
$('overlay').style.display = 'none';
// $('showResult').innerHTML = "<p>压缩前图片大小为:"+result1+"<br/><p>压缩前图片宽度为:"+result2+"<br/><p>压缩前图片高度为:"+result3+"<br/><p>压缩后图片宽度为:"+result4+"<br/><p>压缩后图片高度为:"+result5+"</p><p class='small'>压缩后的图片大小,可通过nodejs或者后台获取!</p>" ;
};
img.src = res;
};
function getCompressRate(allowMaxSize, fileSize) { //计算压缩比率,size单位为MB
var compressRate = 1;
if(fileSize / allowMaxSize > 4) {
compressRate = 0.5;
} else if(fileSize / allowMaxSize > 3) {
compressRate = 0.6;
} else if(fileSize / allowMaxSize > 2) {
compressRate = 0.7;
} else if(fileSize > allowMaxSize) {
compressRate = 0.8;
} else {
compressRate = 0.9;
}
result6 = compressRate;
return compressRate;
}
function $(id) {
if(typeof id === 'string' && id.constructor === String) {
return document.getElementById(id);
} else {
return;
}
}
function uploadimg() {//点击上传
if (file!=null) {
$('overlay').style.display = 'flex';
var xmlhttp = null;
var formData = new FormData(); //这里连带form里的其他参数也一起提交了,如果不需要提交其他参数可以直接FormData无参数的构造函数
formData.append("imgfile", convertBase64UrlToBlob(dataUrl));//将压缩后的图片转为bolb对象上传
var f = convertBase64UrlToBlob(dataUrl);
var url="http://xxx.xxx.com/uploadImg.php"
if(window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else if(window.ActiveXObject) {
xmlhttp = new ActiveXObject();
}
xmlhttp.open("POST", url, true);
xmlhttp.send(formData);
xmlhttp.onload = function(e) {
if(this.status == 200) {
$('overlay').style.display = 'none';
console.log(this.responseText);
alert(this.responseText);
}
}
};
} else{
alert("请点击头像选择图片");
}
}
/**
* 将以base64的图片url数据转换为Blob
* @param urlData
* 用url方式表示的base64图片数据
*/
function convertBase64UrlToBlob(urlData) {
var bytes = window.atob(urlData.split(',')[1]); //去掉url的头,并转换为byte
//处理异常,将ascii码小于0的转换为大于0
var ab = new ArrayBuffer(bytes.length);
var ia = new Uint8Array(ab);
for(var i = 0; i < bytes.length; i++) {
ia[i] = bytes.charCodeAt(i);
}
return new Blob([ab], {
type: 'image/png'
});
}
</script>
</body>
</html>

老马黑科技


