angularJS 以 $http 上傳檔案

  • 167
  • 0

angularJS 透過轉換將檔案放到變數內,利用$http傳入server

amd.run(['$rootScope', '$http',
    function ($rootScope, $http) {
        $rootScope.request = {};
        $rootScope.apply = function () {
            $http({
                method: 'POST',
                url: '/Activity/Apply',
                encType: 'multipart/form-data', // 檔案編碼部分
                headers: { 'Content-Type': undefined },
                transformRequest: function (data, headersGetter) {
                    var formData = new FormData();
                    angular.forEach(data, function (value, key) {
                        formData.append(key, value);
                    });
                    var headers = headersGetter();
                    delete headers['Content-Type'];
                    return formData;
                },
                data: $rootScope.request
            }).then(function (result) {
                var strResult;
                if (result.data) {
                    strResult = "申請成功!";
                    $rootScope.request = { 'Type': $rootScope.request.Type, 'USeagate': '無購買', 'UTForce': '無購買' };
                }
                else strResult = "申請失敗,請稍候再試!";
                alert(strResult);
            }, function (error) {
                alert('網路錯誤,請稍候再試!');
            });
        };
    }
]);

amd.directive('input', function () { // 轉換 input 內資料
    return {
        restrict: 'E',
        scope: {
            ngModel: '=',
            ngChange: '&',
            type: '@'
        },
        link: function (scope, element, attrs) {
            if (attrs.type.toLowerCase() !== 'file') return;
            element.bind('change', function (event) {
                var file = event.target.files[0];
                var ext = event.target.value.substring(event.target.value.lastIndexOf('.')).toUpperCase();
                if (ext !== ".BMP" &&
                    ext !== ".PNG" &&
                    ext !== ".JPG" &&
                    ext !== ".JPEG") {
                    alert('檔案限制 bmp, png, jpeg, jpg 格式!');
                    scope.ngModel = null;
                    return;
                } else if (file.size > 1024 * 1024 * 10) {
                    alert('檔案不能超過 10 MB!');
                    scope.ngModel = null;
                } else scope.ngModel = event.target.files[0];
                scope.$apply();
                scope.ngChange();
            });
        }
    };
});