欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

AngularJS向后端ASP.NET API控制器上传文件

程序员文章站 2022-06-02 23:23:15
本文实例介绍了前端angularjs向后端asp.net web api上传文件的实现方法,具体内容如下 首先服务端: public class file...

本文实例介绍了前端angularjs向后端asp.net web api上传文件的实现方法,具体内容如下

首先服务端:

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);
    
    //文件名类似"bodypart_26d6abe1-3ae1-416a-9429-b35f15e6e5d5"这样的格式
    var originalfilename = getdeserializedfilename(result.filedata.first());
    
    var uploadfileinfo = new fileinfo(result.filedata.first().localfilename);
    
    //如果前端无表单数据,这里注销
    var filleuploadobj = getformdata<uploaddatamodel>(result);
    
    var returndata = "returntest";
    return this.request.createresponse(httpstatuscode.ok, new {returndata});
  }
  
  private multipartformdatastreamprovider getmultipartprovider()
  {
    //图片的上传路径
    var uploadfolder = "~/app_data/fileuploads";
    
    //获取根路径
    var root = httpcontext.current.server.mappath(uploadfolder);
    
    //创建文件夹
    directory.createdirectory(root);
    return new multipartformdatastreamprovider(root);
  }
  
  //从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;
  }
  
  //获取反序列化文件名
  private string getdeserializedfilename(multipartfiledata filedata)
  {
    var filename = getfilename(filedata);
    return jsonconvert.deserializedobject(filename).tostring();
  }
  
  //获取文件名
  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;}
}
 

客户端主页面:

index.html

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

引用:

  • 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

upload.html部分视图页用来接受文件。

upload.html

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

app.js模块依赖和全局配置。

app.js

'use strict'

angular.module('angularuploadapp',[
  'ngcookies',
  'ngresource',
  'ngsanitize',
  'ngroute',
  'angularfileupload'
])
.config(function($routeprovider){
  $routeprovider
    .when('/', {
      templateurl: 'upload.html',
      controller: 'uploadctrl'
    })
    .otherwise({
      resirectto: '/'
    })
})

控制器提供上传和取消上传的方法。

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

以上就是前端angularjs向后端asp.net web api上传文件的实现方法,希望对大家的学习有所帮助。