首頁  >  文章  >  後端開發  >  asp.net core實作檔案上傳功能

asp.net core實作檔案上傳功能

高洛峰
高洛峰原創
2017-02-07 11:42:122051瀏覽

本文實例為大家分享了單一檔案上傳、多檔案上傳的功能,供大家參考,具體內容如下

單一檔案上傳
 上傳檔案在Web應用程式中是常見的功能。在asp.net core中上傳檔案並保存在伺服器上,是很容易的。下面就來示範怎麼樣在 ASP.NET Core專案中進行檔案上傳。
 首先,建立一個 asp.net core 項目,然後在Controller檔案件新增一個HomeController,然後在 Views 資料夾的 Home 資料夾裡新增一個 New.cshtml 視圖檔。如下圖: 

asp.net core实现文件上传功能

新增一個UserViewModel.cs在Model 資料夾中, 程式碼如下:

public class UserViewModel
{
  [Required]
  [Display(Name = "姓名")]
  public string Name { get; set; }
 
  [Required]
  [Display(Name = "身份证")]
  [RegularExpression(@"^(\d{15}$|^\d{18}$|^\d{17}(\d|X|x))$", ErrorMessage = "身份证号不合法")]
  public string IdNum { get; set; }
 
  public string IdCardImgName { get; set; }
 
  [Required]
  [Display(Name = "身份证附件")]
  [FileExtensions(Extensions = ".jpg,.png", ErrorMessage = "图片格式错误")]
  public IFormFile IdCardImg { get; set; }
}


然後新增一個New.cshtml 視圖檔案在Views 資料夾中:中,新增頁面對應的Action 方法:

@model UserViewModel
 
<form asp-controller="Home" role="form" asp-action="New" enctype="multipart/form-data" method="post">
  <div class="form-group">
    <label asp-for="Name"></label>
    <input type="text" class="form-control" asp-for="Name" />
  </div>
  <div class="form-group">
    <label asp-for="IdNum"></label>
    <input type="text" class="form-control" asp-for="IdNum" />
  </div>
  <div class="form-group">
    <label asp-for="IdCardImg"></label>
    <input type="file" asp-for="IdCardImg" />
    <p class="help-block">上传。</p>
  </div>
  <button type="submit" class="btn btn-default">提交</button>
</form>


多檔案上傳


多檔案上傳和單一檔案上傳類似,表單的ViewModel 使用ICollection ,然後表單的 加上mulpitle就可以了(只支援H5)。 

範例原始碼
 註:範例資料儲存使用的 Sqlite ,Code First方式產生資料庫。

更多asp.net core實作檔案上傳功能相關文章請關注PHP中文網!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn