html代码如下:
<div class="am-panel-hd">照片</div>
<div class="am-panel-bd" style="text-align: center;">
<div class="am-form-group am-form-file">
<button type="button" class="am-btn am-btn-default am-btn-sm">
<img id="photo" src="./assets/i/img/photo.png"> </button>
<input type="file" name="file" id="photofile" accept="image/*"/>
</div>
</div>
JavaScript代码如下:
var photo = '';
//免冠照片上传
$('#photofile').change(function(){
var file = this.files[0];
fileType = file.type;
//判断类型是不是图片
if(!/image\/\w+/.test(file.type)){
alert("请确保文件为图像类型");
return false;
}
var fileReader = new FileReader();
fileReader.readAsDataURL(file);
fileReader.onload = function(event){
var result = event.target.result; //返回的dataURL
var image = new Image();
image.src = result;
image.onload = function(){ //创建一个image对象,给canvas绘制使用
var cvs = document.createElement('canvas');
var scale = 1;
if(this.width > 1000 || this.height > 1000){ //1000只是示例,可以根据具体的要求去设定
if(this.width > this.height){
scale = 250 / this.width;
}else{
scale = 250 / this.height;
}
}
cvs.width = this.width*scale;
cvs.height = this.height*scale; //计算等比缩小后图片宽高
var ctx = cvs.getContext('2d');
ctx.drawImage(this, 0, 0, cvs.width, cvs.height);
var newImageData = cvs.toDataURL(fileType, 0.8); //重新生成图片,<span style="font-family: Arial, Helvetica, sans-serif;">fileType为用户选择的图片类型</span>
var sendData = newImageData.replace("data:"+fileType+";base64,",'');
$.ajax({
type: "post",
url: "http://192.168.168.136:80/chapter2/uploadpictrue",
data: {img:sendData},
dataType :"jsonp",
jsonp: "callback",
success: function (data) {
if(data.status == 1)
{
photo = JSON.stringify(data.content);
$("#photo").attr("src",newImageData);
}
},
error: function () {
//alert("上传失败");
}
});
}
}
});