本文實(shí)例為大家分享了單文件上傳、多文件上傳的功能,供大家參考,具體內(nèi)容如下
單文件上傳
上傳文件在Web應(yīng)用程序中是一個(gè)常見的功能。在asp.net core中上傳文件并保存在服務(wù)器上,是很容易的。下面就來演示一下怎么樣在 ASP.NET Core項(xiàng)目中進(jìn)行文件上傳。
首先,創(chuàng)建一個(gè) asp.net core 項(xiàng)目,然后在Controller文件件添加一個(gè)HomeController,然后在 Views 文件夾的 Home 文件夾里添加一個(gè) New.cshtml 視圖文件。如下圖:
添加一個(gè) UserViewModel.cs在 Model 文件夾中 , 代碼如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
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 = "身份證號(hào)不合法" )] public string IdNum { get ; set ; } public string IdCardImgName { get ; set ; } [Required] [Display(Name = "身份證附件" )] [FileExtensions(Extensions = ".jpg,.png" , ErrorMessage = "圖片格式錯(cuò)誤" )] public IFormFile IdCardImg { get ; set ; } } |
然后添加一個(gè) New.cshtml 視圖文件在 Views 文件夾中:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
@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 > |
在 HomeController 中,添加頁面對(duì)應(yīng)的 Action 方法:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
[HttpPost] public IActionResult New([FromServices]IHostingEnvironment env, [FromServices]AppDbContext dbContext, UserViewModel user) { var fileName = Path.Combine( "upload" , DateTime.Now.ToString( "MMddHHmmss" ) + ".jpg" ); using (var stream = new FileStream(Path.Combine(env.WebRootPath, fileName), FileMode.CreateNew)) { user.IdCardImg.CopyTo(stream); } var users = dbContext.Set<User>(); var dbUser = new User() { Name = user.Name, IdCardNum = user.IdNum, IdCardImgName = fileName }; users.Add(dbUser); dbContext.SaveChanges(); return RedirectToAction(nameof(Index)); } |
運(yùn)行程序,查看表單:
多文件上傳
多文件上傳和單文件上傳類似,表單的 ViewModel 使用 ICollection<IFromFile> ,然后表單的<input type="file" asp-for="IdCardImg" mulpitle /> 添加上mulpitle就可以了(只支持 H5)。
示例源碼
注:示例數(shù)據(jù)存儲(chǔ)使用的 Sqlite ,Code First方式生成數(shù)據(jù)庫。
示例代碼已經(jīng)上傳至 github: https://github.com/yuleyule66/AspNetCoreFileUpload
本文地址:http://www.cnblogs.com/savorboard/p/5599563.html
作者博客:Savorboard
以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持服務(wù)器之家。