The AngularJS backend ASP. NET API controller uploads the file

  • 2020-12-18 01:44:32
  • OfStack

This paper introduces the implementation method of front-end AngularJS and back-end ASP. NET Web API upload file by example, the specific content is as follows

First, the server:


public class FilesController : ApiController
{
  //using System.Web.Http
  [HttpPost]
  public async Task<HttpResponseMessage> Upload()
  {
    if(!Request.Content.IsMimeMultipartContent())
    {
      this.Request.CreateResponse(HttpStatusCode.UnsuportedMediaType);
    }
    
    var provider = GetMultipartProvider();
    var result = await Request.Content.ReadAsMultipartAsync(provider);
    
    // Similar file name "BodyPart_26d6abe1-3ae1-416a-9429-b35f15e6e5d5" This format 
    var originalFileName = GetDeserializedFileName(result.FileData.First());
    
    var uploadFileInfo = new FileInfo(result.FileData.First().LocalFileName);
    
    // If there is no form data in the front end, log out here 
    var filleUploadObj = GetFormData<UploadDataModel>(result);
    
    var returnData = "ReturnTest";
    return this.Request.CreateResponse(HttpStatusCode.OK, new {returnData});
  }
  
  private MultipartFormDataStreamProvider GetMultipartProvider()
  {
    // The upload path of the picture 
    var uploadFolder = "~/App_Data/FileUploads";
    
    // Get the root path 
    var root = HttpContext.Current.Server.MapPath(uploadFolder);
    
    // Create folder 
    Directory.CreateDirectory(root);
    return new MultipartFormDataStreamProvider(root);
  }
  
  // from Provider Gets the form data 
  private object GetFormData<T>(MultipartFormDataStreamProvider result)
  {
    if(result.FormData.HasKeys())
    {
      var unescapedFormData = Uri.UnescapeDataString(result.FormData.GetValues(0).FirstOrDefault() ?? String.Empty);
      
      if(!String.IsNullOrEmpty(unescapedFormData))
      {
        return JsonConvert.DeserializeObject<T>(upescapedFormData);
      }
    }
    return null;
  }
  
  // Gets the deserialized file name 
  private string GetDeserializedFileName(MultipartFileData fileData)
  {
    var fileName = GetFileName(fileData);
    return JsonConvert.DeserializedObject(fileName).ToString();
  }
  
  // Get file name 
  public string GetFileName(MultipartFileData fileData)
  {
    return fileData.Headers.ContentDisposition.FileName;
  }
}

UploadDataModel.cs


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

Client home page:

index.html


<div ng-include="'upload.html'"></div>

Reference:

angular-file-upload-shim.js
angular.js
angular-file-upload.js
angular-cookies.js
angular-resource.js
angular-sanitize.js
angular-route.js
app.js
upload.js

Part of the ES42en.html view page is used to accept files.

upload.html


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

app. js module dependencies and global configuration.

app.js


'use strict'

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

The controller provides methods to upload and cancel uploads.

upload.js


'use strict';

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

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

Above is the front-end AngularJS and the back-end ES67en. NET Web API upload file implementation method, hope to help you learn.


Related articles: