在Angular JS中上传后显示图像?

时间:2013-11-14 19:05:56

标签: javascript angularjs file-upload

我有一个问题。所以我发现你可以用HTML上传图像,我使用了以下代码:

<form name="imageUpload" method="post">
    <input type="file" multiple accept = image/* name="uploadField"/>
</form>

然而,鉴于使用AngularJS,我想知道是否有办法在上传图像时在屏幕上的另一个位置显示图像。如果有人可以指出我在正确的方向,那将是伟大的!谢谢!

2 个答案:

答案 0 :(得分:8)

这是更多的JavaScript问题。正如在这里所回答的this answer。角度应该是这样的:

    <!doctype html>
<html lang="en">
<head >
    <meta charset="UTF-8">
    <title>Upload Image</title>
    <script type="text/javascript" src="angular.min.js"></script>

    <script type="text/javascript">
        angular.module('myApp', []).

        controller('UploadCtrl', ['$scope', function (scope) {
            scope.image = "";
        }]).

        directive('myUpload', [function () {
            return {
                restrict: 'A',
                link: function (scope, elem, attrs) {
                    var reader = new FileReader();
                    reader.onload = function (e) {
                        scope.image = e.target.result;
                        scope.$apply();
                    }

                    elem.on('change', function() {
                        reader.readAsDataURL(elem[0].files[0]);
                    });
                }
            };
        }]);
    </script>
</head>
<body ng-app="myApp">
    <div ng-controller="UploadCtrl">
        <img ng-if="image" src="{{image}}" alt="">
        <form action="">
            <input my-upload type="file" name="upload">
        </form>
    </div>

</body>
</html>

答案 1 :(得分:-1)

你可以像我一样做一些事情:Plunker

<!DOCTYPE html>
<html ng-app="app">

  <head>
    <link data-require="bootstrap-css@*" data-semver="3.0.2" rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.2/css/bootstrap.min.css" />
    <script data-require="angular.js@1.2.0" data-semver="1.2.0" src="http://code.angularjs.org/1.2.0/angular.js"></script>
    <link rel="stylesheet" href="style.css" />
    <script type="text/javascript" src="script.js"></script>
  </head>

  <body ng-controller="MainCtrl" >
    <canvas image-display file-data="{{data}},{{mimeType}},{{fileName}}"></canvas>
  </body>
</html>