0

類似的問題已經被問過太多次了,但沒有明確的答案,我仍然無法讓我的工作。HttpPostedFileBase爲空 - 將文件從AngularJS發佈到MVC

這是在C#中的模型

public class SubmitModel 
{ 
    public string Name { get; set; } 
    public HttpPostedFileBase File { get; set; } 
    public IEnumerable<HttpPostedFileBase> Files { get; set; } 
} 

這是MVC編碼

[HttpPost] 
public ActionResult Test(SubmitModel model) 
{ 
    // Here model.File and model.Files is always null 
} 

這是我提交使用AngularJS

var data = { 
    name: scope.name,  // This is passed to MVC successfully 
    file: scope.files[0], // Doesn't even work with single file 
    files: scope.files // This is a FileList 
}; 
$http.post("/umbraco/surface/MyController/Test", data).success(...); 

如果你想知道我是怎麼轉讓scope.files

$('#upload').on('change', function (e) { 
    scope.$apply(function() { 
     scope.files = e.target.files; 
    }); 
}); 

有人能看到我失蹤的東西嗎?

回答

1

解決了!

這是它應該如何在MVC提交

var data = new FormData(); 
angular.forEach(scope.item, function (value, key) { 
    if (key == "files") { 
     for (var i = 0; i < value.length; i++) { 
      data.append(value[i].name, value[i]); // Filename:File 
     } 
    } else { 
     data.append(key, value); 
    } 
}); 

$http.post("/umbraco/surface/MyController/Test", data, { 
       transformRequest: angular.identity, 
       headers: { 'Content-Type': undefined } 
      }).success(...); 

然後,我們從Request.Files文件,它不會在模型中。

[HttpPost] 
public ActionResult Test(SubmitModel model) 
{ 
    var files = Request.Files; // a collection of HttpPostedFileBase 
    Save(model, files); 
} 

更多信息:
https://uncorkedstudios.com/blog/multipartformdata-file-upload-with-angularjs
http://www.codeproject.com/Tips/878730/File-Upload-Using-AngularJS-and-ASP-NET-MVC

相關問題