首页 文章

使用AngularJs显示图像和上传文件的预览

提问于
浏览
0

我希望使用AngularJs上传HTML5的输入类型=“文件”的文件/图像,当用户上传图像时显示预览 . 所以我用这种方式创建了自定义指令:

var modulo = angular.module('myApp', []);

modulo.directive('fileModel', function () {
    return {
        restrict: 'AEC',
        link: function(scope, element, attrs) {
            element.bind('change', function (event) {
                //Take the object
                var fetchFile = event.target.files[0];
                //emit the object upward
                scope.$emit('fileSelected', fetchFile);
            });            
        }
    };
});

现在我在拿走对象(文件/图像)时显示我的控制器,并且我希望显示预览 .

modulo.controller('myController', function ($scope, $http) {

    var files;

    $scope.$on('fileSelected', function(event, fetchFile) {
        //Receive the object from another scope with emit
        files = fetchFile;
        var reader = new FileReader();

        reader.onloadend = function () {
            //Put the object/image in page html with scope
            $scope.content = reader.fetchFile;
        }; 
    });
});

最后,我展示了我希望在输入文件中显示预览的html页面 .

<html ng-app="myApp">
    <head>
        <title>TODO supply a title</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <script src="js/libs/angular.js/angular.js"></script>
        <script src="script.js"></script>
        <script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
    </head>
    <body ng-controller="myController">

        <h1>Select file</h1>
        <input type="file" file-model/>
        <img ng-src="{{content}}"/>
        <div>
            <button ng-click="send()">
                send
            </button>
        </div>
    </body>
</html>

通过这种方式我也没有获得预览,在这个片段中没有用Json发送图像的功能,我会这样做 . 我该如何解决这个问题?谢谢!

1 回答

  • 2

    您必须将读取的文件数据转换为Base 64字符串格式 . 然后,您可以使用该基础64数据来显示图像 .

    <img src='data:image/jpeg;base64,<!-- base64 data -->' />
    

    您可以轻松地将此base 64数据传输到服务器,因为它只是一个字符串 .

相关问题