AngularJS uploads files to the backend ASP. net api controller, and angularjsapi
This document introduces how AngularJS uploads files to ASP. NET Web APIs.
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); // file name format like "BodyPart_26d6abe1-3ae1-416a-9429-b35f15e6e5d5" var originalFileName = GetDeserializedFileName (result. fileData. first (); var uploadFileInfo = new FileInfo (result. fileData. F Irst (). localFileName); // if there is no form data at the front end, cancel var filleUploadObj = GetFormData <UploadDataModel> (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 <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 ;}// 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
<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
Some view pages of upload.html are used to accept files.
Upload.html
<div ng-controller="UploadCtrl" <input type="file" ng-file-select="onFileSelect($files)" multiple></div>
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.
Articles you may be interested in:
- ASP. NET uploads files through Remoting service
- Asp.net FCKEditor 2.6.3 you are not authorized to upload files. solution:
- ASP. NET code for Advanced file type judgment when uploading files
- JQuery. uploadify
- Asp.net simulates the submission of a file upload form (simulate file upload through http)
- How to restrict the size of files uploaded in asp.net
- Asp.net implements the instance code to display the local absolute path for uploading files
- Implementation Code of Asp. Net simulating form submission and File Upload
- Asp.net fileupload control uploads files and multiple files
- In asp.net, MVC uses Iframe to implement brushless newest file upload.