2015年11月2日 星期一

angularjs 1.x upload image and preview

<html>
<head>
    <meta charset="utf-8" />
    <title></title>
    <script src="scripts/angular.min.js"></script>
    <script>
        var app = angular.module('myApp', []);
 
        app.controller('homeCtrl', function ($scope, $http) {
 
            $scope.imageSources = [];
            //  預覽
            $scope.onPreviewImage = function (files) {
                var i = 0, length = files.length, reader;
                $scope.imageSources = [];
                for (= 0; i < length; i++) {
                    reader = new FileReader();
                    reader.onload = function (event) {
                        $scope.imageSources.push(event.target.result);
                        $scope.$apply();
                    };
                    reader.readAsDataURL(files[i]);
                }
            };
            // 上傳檔案
            $scope.onUploadFile = function (files) {
                var fd = new FormData(), length = files.length, i;
                for (= 0; i < length; i++) {
                    fd.append('files', files[i]); // 後端(MVC)接收的變數為 IEnumerable<HttpPostedFileBase> files
                }
                /* undefined Content-Type and transformRequest: angular.identity that
                 * give the $http the ability to choose the right Content-Type
                 * and manage the boundary needed when handling multipart data.
                 */
                $http.post('Upload', fd, { // 上傳
                    withCredentials: true,
                    headers: { 'Content-Type': undefined },
                    transformRequest: angular.identity
                });
            };
        });
    </script>
</head>
<body ng-app="myApp" ng-controller="homeCtrl">
    <input type="file" multiple onchange="angular.element(this).scope().onPreviewImage(this.files)" accept="image/*" />
    <img ng-repeat="img in imageSources" ng-src="{{img}}" />
    <button ng-click="onUploadFile()">上傳</button>
</body>
</html>


Copy and Paste Formatting with Visual Studio’s Dark Them :
https://codinglifestyle.wordpress.com/2013/05/17/copy-and-paste-formatting-with-visual-studios-dark-theme/

沒有留言: