时间:2021-07-01 10:21:17 帮助过:17人阅读
如何实现angularjs图片上传,并获取图片路径
我一般是自己写表单提交,主要原理就是利用一个隐藏的input,然后自己写指令到input上,代码可参照如下:
function checkImgType(file) {
var type = file.name.split(".");
if (type[type.length - 1] != 'png' && type[type.length - 1] != 'jpg' && type[type.length - 1] != 'jpeg') {
return false;
}
return true;
};
$scope.upload = function(name, imgUrl) {
var fileObj = document.getElementById(name).files[0];
if (fileObj) {
$scope.imgloading[imgUrl] = true;
}
if (!checkImgType(fileObj)) {
alert("图片格式错误,只支持png,jpg,jpeg格式");
return;
}
var form = new FormData();
form.append("file", fileObj);
var xhr = new XMLHttpRequest();
xhr.open("POST",httpBase+ "upload", true);
function callback() {
if (xhr.readyState == 4) {
$timeout(function() {
var data = angular.fromJson(xhr.responseText);
$scope.$apply(function() {
$scope.goods[name] = data.statusMessage;
});
}, 3000);
}
};
xhr.onreadystatechange = callback;
xhr.send(form);
};
html
补充下指令
.directive("ltFile", function() {
return {
restrict: 'AE',
link: function(scope, elm, attr, ngModelCtrl) {
elm.bind('change', function(newValue,oldValue) {
scope.$apply(function() {
eval("scope." + attr.fileFn);
})
});
}
};
})
https://github.com/danialfarid/ng-file-upload