【问题标题】:Show preview of Image and upload file with AngularJs使用 AngularJs 显示图像预览和上传文件
【发布时间】:2015-07-02 01:20:14
【问题描述】:

我想使用 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>

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

【问题讨论】:

    标签: javascript jquery angularjs file-upload angularjs-directive


    【解决方案1】:

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-06-29
      • 2012-06-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-01
      • 2015-10-18
      相关资源
      最近更新 更多