AngularJS uploads a file _ AngularJS to the backend ASP. NETAPI Controller

Source: Internet
Author: User
This article mainly introduces AngularJS to backend ASP. for more information about how NETAPI controller uploads files, refer to the examples in this article to introduce AngularJS to ASP. NET Web API File Upload implementation method, the specific content is as follows

First, the server:

Public class FilesController: ApiController {// using System. Web. Http [HttpPost] public async Task
 
  
Upload () {if (! Request. content. isMimeMultipartContent () {this. request. createResponse (HttpStatusCode. unsuportedMediaType);} var provider = GetMultipartProvider (); var result = await Request. content. readAsMultipartAsync (provider); // file name format like "BodyPart_26d6abe1-3ae1-416a-9429-b35f15e6e5d5" var originalFileName = GetDeserializedFileName (result. fileData. first (); var uploadFileInfo = new FileInfo (result. fileData. first (). localFileName); // if there is no form data at the front end, cancel var filleUploadObj = GetFormData here
  
   
(Result); var returnData = "ReturnTest"; return this. request. createResponse (HttpStatusCode. OK, new {returnData});} private MultipartFormDataStreamProvider GetMultipartProvider () {// upload path of the image var uploadFolder = "~ /App_Data/FileUploads "; // obtain the root path var root = HttpContext. current. server. mapPath (uploadFolder); // create a folder Directory. createDirectory (root); return new MultipartFormDataStreamProvider (root);} // obtain form data from the Provider private object GetFormData
   
    
(MultipartFormDataStreamProvider result) {if (result. FormData. HasKeys () {var unescapedFormData = Uri. UnescapeDataString (result. FormData. GetValues (0). FirstOrDefault ()?? String. Empty); if (! String. IsNullOrEmpty (unescapedFormData) {return JsonConvert. DeserializeObject
    
     
(UpescapedFormData);} return null;} // get the deserialization file name private string GetDeserializedFileName (MultipartFileData fileData) {var fileName = GetFileName (fileData); return JsonConvert. deserializedObject (fileName ). toString ();} // get the 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 homepage:

Index.html

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

Some view pages of upload.html are used to accept files.

Upload.html

App. js module dependency 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 the upload and cancel methods.

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();    }  })

The above is how AngularJS uploads files to the backend ASP. NET Web API. I hope this will be helpful for your learning.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.