Angularjs:有没有办法,我可以在不使用文件阅读器的情况下向用户显示由他选择的图像的图像预览。
以下是我的代码试图用它
<input type="file" file-model="myFile"/><br><br>
<button ng-click="uploadFile()">Upload</button>
<img src = {{image}}>
<script>
var mainApp = angular.module("mainApp", []);
mainApp.controller('myController', function ($scope,$http) {
$scope.uploadFile = function(){
var file = $scope.myFile;
var fd = new FormData();
//fd will be an file object now, I want this to be converted to img
$scope.image = Resultimage;
};
});
mainApp.directive('fileModel', ['$parse', function ($parse) {
return {
restrict: 'A',
link: function(scope, element, attrs) {
var model = $parse(attrs.fileModel);
var modelSetter = model.assign;
element.bind('change', function(){
scope.$apply(function(){
modelSetter(scope, element[0].files[0]);
}); //end of scope.$apply
});//end of link
}
};
}]);
答案 0 :(得分:0)
在您的情况下,您可以将$ scope.image设置为等于URL.createObjectURL(file);
<script>
function readfile(el) {
let file = el.files[0];
document.getElementById("previewImage").src = URL.createObjectURL(file);
}
</script>
<img id="previewImage">
<input type='file' onchange='readfile(this)'/>