最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to bind image source to file object in angular - Stack Overflow

programmeradmin3浏览0评论

I have two elements one file and another image

<input type='file' id='myfile' />
<img id='myImg' >

When i select image using file browse, my image object should be updated with the selected image How can i achieve this using angular?

I have two elements one file and another image

<input type='file' id='myfile' />
<img id='myImg' >

When i select image using file browse, my image object should be updated with the selected image How can i achieve this using angular?

Share Improve this question asked Nov 24, 2014 at 6:28 debianmasterdebianmaster 5038 silver badges19 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 4

Use FileReader for this. For example:

html

<div ng-app="app" ng-controller="Controller">
    <img ng-src="{{loadedFile}}" alt="" />
    <input type="file" value="load" onchange="angular.element(this).scope().fileLoaded(this)" />
</div>

code

function Controller($scope) {
    $scope.fileLoaded = function (e) {
        var tgt = e.target || window.event.srcElement,
            files = tgt.files,
            fileReader;

        if (FileReader && files && files.length) {
            var fileReader = new FileReader();
            fileReader.onload = function () {

                $scope.loadedFile = fileReader.result;
                $scope.$apply();
            }
            fileReader.readAsDataURL(files[0]);
        } else {
            // Not supported
        }
    };
});

Look fiddle

You can use ng-flow

Check out Gallery upload from here http://flowjs.github.io/ng-flow/

Hope this helps you!

Javascript way of doing this is on onchange event is

var file = event.target.files[0];
var reader = new FileReader();
reader.onload = function (e) {
    $('#myImg').attr('src', e.target.result);
}
reader.readAsDataURL(file);

I need it in Angular

发布评论

评论列表(0)

  1. 暂无评论