שאלו אותי, כיצד ניתן להעלות קבצים באנגולר (1) עם מידע נוסף (למשל שם פרטי ושם משפחה).

    ישנם מספר גדול של קודים ברשת כיצד להעלות קבצים בעזרת אנגולר, להלן הקוד הבסיסי ביותר.

    <body ng-controller="ctrl">
     
        <div> 
            <input type="file" id="file" />
            <input type="text" ng-model="details.firstName" />
            <input type="text" ng-model="details.lastName" />
     
            <button ng-click="upload()">Save</button>
        </div>
    </body>

     

    שימו לב של – input של הקבצים אין מודל (הרבה פעמים העלאת קבצים מתבצעת בעזרת directive שעוטף אותו)

     

    angular.module('app', [])
        .controller('ctrl', function ($scope, $http) {
            $scope.upload = function () {
                var fd = new FormData();
                fd.append('firstName', $scope.details.firstName);
                fd.append('lastName', $scope.details.lastName);
                fd.append('file', document.getElementById('file').files[0]);
     
                $http({
                    url: '/home/upload',
                    method: 'POST',
                    data: fd,
                    headers: { 'Content-Type': undefined },
                    transformRequest: angular.identity
                }).then(function (res) {
                    console.log(res.data);
                });
            };
        });

     

    בקוד כאן (שהוא בסיסי ביותר) אנחנו משתמשים בתכונה של HTML5 הנקרא FormData,  אליו אנחנו מעתיקים את המידע מתוך המודל, כאשר בסוף התהליך אנחנו דואגים להוסיף את שני המאפיינים של ה – headers וה – transformRequest שיגרמו לאנגולר להעלות את הקבוץ ואת המידע כמו שצריך.

     

    בצד השרת (כאן כבר תלוי איזה שרת) הקוד הוא פשוט ביותר

     

    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }
     
        public ActionResult Upload(MyDto model)
        {
            return null;
        }
    }
     
    public class MyDto
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public HttpPostedFileBase File { get; set; }
    }