2016-08-21 13 views
1

服務器端代碼:如何使用HttpPostedFileBase中的WebAPI模型(POST操作)

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

將角客戶端代碼這樣的工作?

$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存儲來存儲上傳的文件。

+0

你需要上傳使用AngularJS文件? – Sampath

+0

遐就是這樣。 –

回答

0

這是它的偉大指示。 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}, ...})...; 
     } 
    } 
}]); 
+0

我更關心服務器端的東西。我真的不需要'ng-file-upload',沒有它可以做。正如在問題中,我想用模型中的其他數據發佈多個文件。如果您可以演示如何使用webapi模型,那就太好了。 –

+0

您也可以使用它來發布多個文件。我也提供了一個WebApi演示鏈接。請參閱。 – Sampath

+0

我看到了您發佈的鏈接。但是,這些文件不作爲webapi模型的一部分發布。 –

相關問題