首页 > 代码库 > chrome用type=file获取图片路径并转base64字符串
chrome用type=file获取图片路径并转base64字符串
1 html页面
<div class="col-sm-2" style="height: 200px;margin-top: 14px;">
<input id="photo" name=" " type="file" value="http://www.mamicode.com/选择图片" ng-model="photoUrl">
<input type="button" ng-click = "uploadPic()" value="http://www.mamicode.com/确定" style="margin-top: 150px;margin-left: 10px;"/>
</div>
2 js里面
$scope.uploadPic = function(){
var obj = document.getElementById("photo");
console.log("13:"+obj.value)
if(obj.value){
var file = obj.files[0]
//注意此处,chrome不支持直接获取文件的绝对路径,需要把文件放到一个中间地址,然后用js获取这个中间地址的绝对路径
var windowURL = window.URL || window.webkitURL;
var dataURL = windowURL.createObjectURL(file);
console.log($(‘#img1‘))
console.log(dataURL)
$(‘#img1‘).attr(‘src‘,dataURL)
var img = document.createElement(‘img‘);
img.src = http://www.mamicode.com/dataURL;
以上是在中间地址放文件的逻辑
var data
img.onload =function() {
//转base64
data = http://www.mamicode.com/getBase64Image(img);
console.log("changdu:"+data.length);
一般浏览器对提交字符串有大小限制,要限定一下,要不会报错
if(data.length<1050000){
console.log(data);
$(‘#img1‘).attr(‘src‘,data)
$scope.pic = {};
$scope.pic.idPark = idPark;
$scope.pic.picture = data;
dataParkSettingAdmin.saveOrUpdateParkPicture(idPark,$scope.pic).success(function(data) {
console.log("shangchuantupian:"+data.result);
})
}else{
app.modalWin.info({title:‘ ‘, content:‘该图片不支持上传‘ });
}
}
}
}
以下是图片转base64字符串的函数
function getBase64Image(img) {
var canvas = document.createElement("canvas");
canvas.width = img.width;
canvas.height = img.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0, img.width, img.height);
var dataURL = canvas.toDataURL("image/png");
return dataURL // return dataURL.replace("data:image/png;base64,", "");
}
chrome用type=file获取图片路径并转base64字符串