dcsimg
Results 1 to 2 of 2

Thread: [RESOLVED] [ASP.NET MVC 5 and AngularJS] Upload File together with JSON Data.

  1. #1

    Thread Starter
    Lively Member FunkySloth's Avatar
    Join Date
    Aug 2016
    Posts
    74

    Resolved [RESOLVED] [ASP.NET MVC 5 and AngularJS] Upload File together with JSON Data.

    Hi Guys,

    I don't know how to upload a file together with JSON model at the same time. Please take a look at my codes:

    Employee Model
    Code:
         Public string Name { get; set; }
         Public string DepartmentId { get; set; }
         Public string DesignationId { get; set; }
         Public byte[] File { get; set; }
         Public HttpPostedFileBase attachment { get; set; }
    Controller
    Code:
    [HttpPost]
    public JsonResult Insert(Employee model, HttpPostedFileBase attachment)
    {
          // Save Method
    }
    View
    Code:
    <input type="text" ng-model="Name">
    <input type="text" ng-model="DepartmentId">
    <input type="text" ng-model="DesignationId">
    <input type="file" ng-model="attachment" onchange="angular.element(this).scope().LoadFileData(this.files)">
    Angular Service
    Code:
    this.saveRecord = function (model, file) {
        var response = $http({
              method: 'post',
              url: '/Employee/Insert',
              headers: { 'Content-Type': undefined },
              data: { model: JSON.stringify(model), attachment: file },
              dataType: 'json'
        });
    }
    Angular Controller
    Code:
    $scope.files = [];
    
    $scope.LoadFileData = function (files) {
          $scope.files = files;
    };
    
    $scope.save = function () {
           var model = {
                 Name: $scope.Name,
                 DepartmentId: $scope.DepartmentId,
                 DesignationId: $scope.DesignationId,
           };
    
            var saveData = myService.insert(model, $scope.files);
    
            saveData.then(function (d) {
                if (d.data.success === true) {
                    $scope.resetInsert();
                    alert('Employee save successfully');
                    loadEmployees();
                } else {
                    alert('Employee not save.');
                }
            }, function (d) {
                alert('Error saving data');
            });
    }
    When I run the program, the Employee model is empty and HttpPostedFileBase is null. Can anyone help me with this?

    Thank you in advance

  2. #2

    Thread Starter
    Lively Member FunkySloth's Avatar
    Join Date
    Aug 2016
    Posts
    74

    Re: [ASP.NET MVC 5 and AngularJS] Upload File together with JSON Data.

    I resolved my problem, all I need is to convert it to FormData together with the file attachment.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Featured


Click Here to Expand Forum to Full Width