SoFunction
Updated on 2025-04-10

AngularJS uploads files to the backend API controller

This article introduces the implementation method of front-end AngularJS uploading files to the back-end Web API. The specific content is as follows

First of all, the server side:

public class FilesController : ApiController
{
  //using 
  [HttpPost]
  public async Task<HttpResponseMessage> Upload()
  {
    if(!())
    {
      ();
    }
    
    var provider = GetMultipartProvider();
    var result = await (provider);
    
    //The file name is similar to "BodyPart_26d6abe1-3ae1-416a-9429-b35f15e6e5d5" format    var originalFileName = GetDeserializedFileName(());
    
    var uploadFileInfo = new FileInfo(().LocalFileName);
    
    //If there is no form data on the front end, cancel here    var filleUploadObj = GetFormData<UploadDataModel>(result);
    
    var returnData = "ReturnTest";
    return (, new {returnData});
  }
  
  private MultipartFormDataStreamProvider GetMultipartProvider()
  {
    //The upload path of the image    var uploadFolder = "~/App_Data/FileUploads";
    
    //Get the root path    var root = (uploadFolder);
    
    //Create a folder    (root);
    return new MultipartFormDataStreamProvider(root);
  }
  
  //Get form data from Provider  private object GetFormData<T>(MultipartFormDataStreamProvider result)
  {
    if(())
    {
      var unescapedFormData = ((0).FirstOrDefault() ?? );
      
      if(!(unescapedFormData))
      {
        return <T>(upescapedFormData);
      }
    }
    return null;
  }
  
  //Get the deserialized file name  private string GetDeserializedFileName(MultipartFileData fileData)
  {
    var fileName = GetFileName(fileData);
    return (fileName).ToString();
  }
  
  //Get file name  public string GetFileName(MultipartFileData fileData)
  {
    return ;
  }
}

public class UploadDataModel
{
  public string testString1{get;set;}
  public string testString2{get;set;}
}
 

Client homepage:

<div ng-include="''"></div>

Quote:










Some view pages are used to accept files.

<div ng-controller="UploadCtrl"
  <input type="file" ng-file-select="onFileSelect($files)" multiple>
</div>

Module dependencies and global configuration.


'use strict'

('angularUploadApp',[
  'ngCookies',
  'ngResource',
  'ngSanitize',
  'ngRoute',
  'angularFileUpload'
])
.config(function($routeProvider){
  $routeProvider
    .when('/', {
      templateUrl: '',
      controller: 'UploadCtrl'
    })
    .otherwise({
      resirectTo: '/'
    })
})

The controller provides methods to upload and cancel uploads.


'use strict';

('angularUploadApp')
  .controller('UploadCtrl', function($scope, $http, $timeout, $upload){
    $ = [];
    $ = {testString1: "Test ring 1", testString2: "Test string 2"};
    
    $ = function ($files) {
      //$files: an array of files selected, each file has name, size, and type.
      for (var i = 0; i < $; i++) {
        var $file = $files[i];
        (function (index) {
          $[index] = $({
            url: "./api/files/upload", // webapi url
            method: "POST",
            data: { fileUploadObj: $ },
            file: $file
          }).progress(function (evt) {
            // get upload percentage
            ('percent: ' + parseInt(100.0 *  / ));
          }).success(function (data, status, headers, config) {
            // file is uploaded successfully
            (data);
          }).error(function (data, status, headers, config) {
            // file failed to upload
            (data);
          });
        })(i);
      }
    }

    $ = function (index) {
      $[index].abort();
    }
  })

The above is the implementation method of front-end AngularJS uploading files to the back-end Web API. I hope it will be helpful to everyone's learning.