2016-12-06 72 views
2

我正嘗試從角度爲1.5x的表單數據上傳文件到.net核心web api控制器。 我的控制器看起來像這樣使用asp.net核心中的表單數據上傳文件

[HttpPost]public async Task<ObjectResult> Create(TutorModel model) 
    { 
    } 

我POST方法

return $http.post("/api/Tutor/createTutor/", 
 
     data, 
 
       { 
 
        withCredentials: false, 
 
        headers: { 'Content-Type': undefined }, 
 
        transformRequest: angular.identity, 
 
        responseType: "arryabuffer" 
 
       }); 
 

 

 
Where data is 
 

 

 
for (var i = 0; i < vm.uploadedFiles.length ; i++) { //vm.upload contains list of file 
 
       data.append(vm.uploadedFiles[i].name, vm.uploadedFiles[i]); 
 
      } 
 
      data.append("tutor", tutor); //tutor is json object

現在,當它發佈到控制器,型號不包含任何屬性值。如果我看到Request.Form.Files,我會在控制器中獲取上傳的文件。發送模型到Post方法的最佳方法是什麼?任何指針?謝謝

+1

https://www.asp.net/web-api/overview/advanced/sending-html-form-data-part-2 - 應該幫助 – Developer

+0

@Developer我尋找asp.net核心例子。感謝您的鏈接,雖然 – Aryan

回答

1

Asp.net核心文檔簡要介紹了該主題。

你的控制器動作就是這樣。

[HttpPost("UploadFiles")] 
public async Task<IActionResult> Post(List<IFormFile> files) 
{ 
    long size = files.Sum(f => f.Length); 

    // full path to file in temp location 
    var filePath = Path.GetTempFileName(); 

    foreach (var formFile in files) 
    { 
     if (formFile.Length > 0) 
     { 
     using (var stream = new FileStream(filePath, FileMode.Create)) 
     { 
      await formFile.CopyToAsync(stream); 
     } 
     } 
    } 

    // process uploaded files 

    return Ok(new { count = files.Count, size, filePath}); 
} 

凡IFormFile具有這些特性

public interface IFormFile 
    { 
    string ContentType { get; } 
    string ContentDisposition { get; } 
    IHeaderDictionary Headers { get; } 
    long Length { get; } 
    string Name { get; } 
    string FileName { get; } 
    Stream OpenReadStream(); 
    void CopyTo(Stream target); 
    Task CopyToAsync(Stream target, CancellationToken cancellationToken = null); 
    } 

注:在關係數據庫中存儲二進制數據時一定要小心,因爲它可以產生不利影響的表現。

這裏閱讀詳細的文章 File Uploads

+0

我想通過viewmodel呢?不能讓我的頭靠近它。我已經成功地傳遞文件和表單數據使用參數,但我想發送json對象與文件。 THX – Aryan

+0

我創建了這兩款車型 – Ahmar

+0

'公共班主任{ 公衆詮釋ID {獲取;集;} 公共字符串名稱{;設置;} } 公共類VM { 公共VM(){ 導師=新導師(); } 公共列表文件{得到;集;} 公共家教{得到;集;}} 爲(VAR I = 0; I Ahmar