【问题标题】:How to use HttpPostedFileBase in WebApi Model (Post Action)如何在 WebApi 模型中使用 HttpPostedFileBase (Post Action)
【发布时间】:2016-12-28 03:45:54
【问题描述】:

服务器端代码:

public class SomeModel
{
    public Int64 Id { get; set; }
    [Required]
    public Int64 From_UserId { get; set; }
    public string Text { get; set; }
    public List<HttpPostedFileBase> Files {get; set;} //<-- Wonder if this is right way ?
}

Action Method in Controller

[HttpPost]
[Route("Upload")]
public IHttpActionResult Upload( SomeModel model)
{
    if (!ModelState.IsValid)
    {
        return BadRequest(ModelState);
    }
    //More code
    return Ok();
}

这样的 Angular 客户端代码可以工作吗?

$http.post("api/upload",{
    Id: 1,
    From_UserId: 1,
    Text: "First File",
    Files: [file1, file2, file3]    //<-These are the ones obtained through file type input 
 }) 

附加信息:使用 Azure 存储存储上传的文件。

【问题讨论】:

  • 你需要使用AngularJS上传文件吗?

标签: c# angularjs azure asp.net-web-api azure-blob-storage


【解决方案1】:

这是一个很好的指令。 ng-file-upload

这里是Demo using Asp.net WebApi

JS

//inject directives and services.
var app = angular.module('fileUpload', ['ngFileUpload']);

app.controller('MyCtrl', ['$scope', 'Upload', function ($scope, Upload) {
    // upload later on form submit or something similar
    $scope.submit = function() {
      if ($scope.form.file.$valid && $scope.file) {
        $scope.upload($scope.file);
      }
    };

    // upload on file select or drop
    $scope.upload = function (file) {
        Upload.upload({
            url: 'upload/url',
            data: {file: file, 'username': $scope.username}
        }).then(function (resp) {
            console.log('Success ' + resp.config.data.file.name + 'uploaded. Response: ' + resp.data);
        }, function (resp) {
            console.log('Error status: ' + resp.status);
        }, function (evt) {
            var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
            console.log('progress: ' + progressPercentage + '% ' + evt.config.data.file.name);
        });
    };
    // for multiple files:
    $scope.uploadFiles = function (files) {
      if (files && files.length) {
        for (var i = 0; i < files.length; i++) {
          Upload.upload({..., data: {file: files[i]}, ...})...;
        }
        // or send them all together for HTML5 browsers:
        Upload.upload({..., data: {file: files}, ...})...;
      }
    }
}]);

【讨论】:

  • 我更关心服务器端的事情。我真的不需要ng-file-upload,可以没有它。与问题一样,我想在模型中发布多个带有其他数据的文件。如果你能演示如何使用 webapi 模型,那就太好了。
  • 你也可以用它来发布多个文件。我也放了一个WebApi演示链接。请看一下。
  • 我看到了您发布的链接。但是,这些文件不会作为 webapi 模型的一部分发布。
  • 这只是一个示例,您需要根据自己的要求进行修改。
  • 你能提供一些不是AngularJS @Sampath的服务器代码
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-09
  • 1970-01-01
相关资源
最近更新 更多