Bài 77: (ASP.NET Razor) Upload file trong Razor Page với IFormFile

Ngày đăng: 12/30/2022 8:23:13 AM

Upload File trong Razor Page

Để upload file thì HTML Form phải sử dụng phương thức post, có thuộc tính enctype="multipart/form-data", phần tử để chọn file upload là <input> với kiểu type="file"

Tạo ra dự án ASP.NET Core Razor Page để thực hành, trong thư mục razor07.uploadfiles gõ lệnh

 dotnet new webapp

Tạo file Pages/UploadOneFile.cshtml và Pages/UploadOneFile.cshtml.cs trong Pages/UploadOneFile.cshtml.cs tạo ra PageModel như sau:

 namespace razor07.uploadfiles.Pages
 {
     public class UploadOneFileModel : PageModel {
         [Required(ErrorMessage = "Chọn một file")]
         [DataType(DataType.Upload)]
         [FileExtensions(Extensions="png,jpg,jpeg,gif")]
         [Display(Name="Chọn file upload")]
         [BindProperty]
         public IFormFile FileUpload { get; set; }
         public async Task OnPostAsync()
         {
             // Code xử lý khi upload file ở đây
         }
     }
 }
 

Model này có thuộc tính kiểu IFormFile nó là dữ liệu File được Upload lên từ Form, đặt thuộc tính này tự động binding khi Form Post lên

Razor Pages/UploadOneFile.cshtml biên tập nội dung

 @page 
 @model UploadOneFileModel
 <form method="post" enctype="multipart/form-data">
     <label asp-for="@Model.FileUpload"></label>
     <input asp-for="@Model.FileUpload" />
     <span asp-validation-formaction="@Model.FileUpload"></span>
 
     <button class="btn btn-danger" asp-page="UploadOneFile">Upload</button>
 </form>

Viết code sử lý upload file, file được copy vào thư mục uploads

 namespace razor07.uploadfiles.Pages {
   public class UploadOneFileModel : PageModel {
 
     private IHostingEnvironment _environment;
     public UploadOneFileModel (IHostingEnvironment environment) {
       _environment = environment;
     }
 
     [Required (ErrorMessage = "Chọn một file")]
     [DataType (DataType.Upload)]
     [FileExtensions (Extensions = "png,jpg,jpeg,gif")]
     [Display (Name = "Chọn file upload")]
     [BindProperty]
     public IFormFile FileUpload { get; set; }
     public async Task OnPostAsync () {
       if (FileUpload != null) {
         var file = Path.Combine (_environment.ContentRootPath, "uploads", FileUpload.FileName);
         using (var fileStream = new FileStream (file, FileMode.Create)) {
           await FileUpload.CopyToAsync (fileStream);
         }
       }
 
     }
 
   }
 }
 

Upload nhiều File trong Razor Page

Khai báo có thuộc tính mảng kiểu IFormFile để có chức năng upload nhiều file, ví dụ:

UploadMulti.cshtml.cs

 using System;
 using System.Collections.Generic;
 using System.ComponentModel.DataAnnotations;
 using System.IO;
 using System.Linq;
 using System.Threading.Tasks;
 using Microsoft.AspNetCore.Hosting;
 using Microsoft.AspNetCore.Http;
 using Microsoft.AspNetCore.Mvc;
 using Microsoft.AspNetCore.Mvc.RazorPages;
 using Microsoft.Extensions.Logging;
 
 namespace razor07.uploadfiles.Pages {
   public class UploadMultiModel : PageModel {
 
     private IHostingEnvironment _environment;
     public UploadMultiModel (IHostingEnvironment environment) {
       _environment = environment;
     }
 
     [Required (ErrorMessage = "Chọn một file")]
     [DataType (DataType.Upload)]
     [FileExtensions (Extensions = "png,jpg,jpeg,gif")]
     [Display (Name = "Chọn file upload")]
     [BindProperty]
     public IFormFile[] FileUploads { get; set; }
     public async Task OnPostAsync () {
       if (FileUploads != null) {
          foreach (var FileUpload in FileUploads)
          {
               var file = Path.Combine (_environment.ContentRootPath, "uploads", FileUpload.FileName);
               using (var fileStream = new FileStream (file, FileMode.Create)) {
                 await FileUpload.CopyToAsync (fileStream);
               }
          }
       }
 
     }
 
   }
 }
 

Trong UploadMulti.cshtml

 @page 
 @model UploadMultiModel
 <form method="post" enctype="multipart/form-data">
     <label asp-for="@Model.FileUploads"></label>
     <input asp-for="@Model.FileUploads" />
     <span asp-validation-formaction="@Model.FileUploads"></span>
 
     <button class="btn btn-danger" asp-page="UploadMulti">Upload</button>
 </form>

Mã nguồn ASP_NET_CORE/razor07.uploadfiles

Nguồn tin: Xuanthulab