在ASP.NET Core Razor Pages页面中上传文件

admin
admin
2022-03-02
分享:

在ASP.NET Core Razor Pages页面中上传文件

导航:

在本视频中,我们将讨论如何使用ASP.NET Core Razor Pages框架将文件上传到服务器。

我们讨论了如何在“编辑 Razor ”页面上显示现有学生数据(姓名,电子邮件和班级),如先前视频中下图所示。

在本视频中,我们将讨论如何删除现有学生照片并上传新照片。

Edit.cshtml 视图


@page "{id:min(1)}"
@model EditModel
@{
    ViewData["Title"] = "编辑";
     // 如果学生没有照片信息,就默认给他一张空照片
    var photoPath = "~/images/" + (Model.Student.PhotoPath ?? "noimage.png");
}

<h1>编辑学生</h1>

<form method="post" class="mt-3"  >
    @*使用隐藏的input标签来存储提交表单时需要的学生id*@
    <input hidden asp-for="Student.Id" />

    @*asp-for TagHelper 负责在处理在不同的标签中显示现有的数据*@
    <div class="form-group row">
        <label asp-for="Student.Name" class="col-sm-2 col-form-label">
        </label>
        <div class="col-sm-10">
            <input asp-for="Student.Name" class="form-control" placeholder="Name">
        </div>
    </div>
    <div class="form-group row">
        <label asp-for="Student.Email" class="col-sm-2 col-form-label"></label>
        <div class="col-sm-10">
            <input asp-for="Student.Email" class="form-control" placeholder="Email">
        </div>
    </div>

    <div class="form-group row">
        <label asp-for="Student.Major" class="col-sm-2 col-form-label"></label>
        <div class="col-sm-10">
            <select asp-for="Student.Major" class="custom-select mr-sm-2"
                    asp-items="Html.GetEnumSelectList<MajorEnum>()">
                <option value="">请选择</option>
            </select>
        </div>
    </div>

    
    <div class="form-group row">
        <label asp-for="Photo" class="col-sm-2 col-form-label"></label>
        <div class="col-sm-10">
            <div class="custom-file">
                @*Photo属性类型是IFormFile,ASP. NET Core会根据这个属性自动创建一个FileUpload控件 *@
                @* 有关更具体的信息在《深入浅出ASP.NET Core》那本书有介绍 *@
                <input asp-for="Photo" class="custom-file-input form-control">
                <label class="custom-file-label">更换图片</label>
            </div>
        </div>
    </div>   
  

 
     @*显示有照片的学生信息*@
    <div class="form-group row col-sm-4 offset-4">
        <img class="imageThumbnail" src="@photoPath" asp-append-version="true" />
    </div>

    <div class="form-group row">
        <div class="col-sm-10">
            <button type="submit" class="btn btn-primary">更新</button>
            <a asp-page="/Students/Index" class="btn btn-primary">取消</a>
        </div>
    </div>
</form>


   @section Scripts {
        <script>
            $(document).ready(function () {
                 
                $('.custom-file-input').on("change", function () {
                    var fileName = $(this).val().split("\\").pop();
                    $(this).next('.custom-file-label').html(fileName);
                });
            });
        </script>
    }

Edit.cshtml.cs


using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using StudentManagement.RazorPage.Models;
using YoYoMooc.StudentManagement.Services;
using System;
using System.IO;

namespace StudentManagement.RazorPage.Pages.Students
{
    public class EditModel : PageModel
    {
        private readonly IStudentRepository _studentRepository;
        private readonly IWebHostEnvironment _webHostEnvironment;

        public EditModel(IStudentRepository studentRepository, IWebHostEnvironment webHostEnvironment)
        {
            _studentRepository = studentRepository;
            _webHostEnvironment = webHostEnvironment;
        }

        //这是显示模板将用于的属性,显示现有的学生数据
        [BindProperty]
        public Student Student { get; set; }

        // 我们使用这个属性来存储和处理新上传的照片
        [BindProperty]
        public IFormFile Photo { get; set; }
       
        public IActionResult OnGet(int id)
        {
            Student = _studentRepository.GetStudent(id);

            if (Student == null)
            {
                return RedirectToPage("/NotFound");
            }

            return Page();
        }


         public IActionResult OnPost(Student student)
        {
            if (Photo != null)
            {
                //上传新照片的时候,需要检查当前学生是否有已经存在的照片,如果有的话,就需要删除它,再上传新照片。
                if (student.PhotoPath != null)
                {
                    string filePath = Path.Combine(_webHostEnvironment.WebRootPath,
                        "images", student.PhotoPath);
                    System.IO.File.Delete(filePath);
                }
                // 将新照片保存到wwwroot/images文件夹中,并更新student 的PhotoPath属性
                student.PhotoPath = ProcessUploadedFile();
            }

            Student = _studentRepository.Update(student);
            return RedirectToPage("Index");
        }


        private string ProcessUploadedFile()
        {
            string uniqueFileName = null;

            if (Photo != null)
            {
                string uploadsFolder = Path.Combine(_webHostEnvironment.WebRootPath, "images");

                uniqueFileName = Guid.NewGuid().ToString() + "_" + Photo.FileName;

                string filePath = Path.Combine(uploadsFolder, uniqueFileName);

                using (var fileStream = new FileStream(filePath, FileMode.Create))
                {
                    Photo.CopyTo(fileStream);
                }
            }

            return uniqueFileName;
        }

    }
}

IStudentRepository.cs

  public interface IStudentRepository
    {
                IEnumerable<Student> GetAllStudents();
                Student GetStudent(int id);
           Student Update(Student updatedStudent);
    }

MockStudentRepository.cs

public class MockStudentRepository : IStudentRepository
    {
        private List<Student> _studentList;

         public MockStudentRepository()
        {
            _studentList = new List<Student>()
            {
                 new Student() { Id = 1, Name = "张三", Major = MajorEnum.ComputerScience, Email = "Tony-zhang@52abp.com" },
            new Student() { Id = 2, Name = "李四", Major = MajorEnum.ElectronicCommerce, Email = "lisi@52abp.com" },
            new Student() { Id = 3, Name = "王二麻子", Major = MajorEnum.Mathematics, Email = "wang@52abp.com" },
            };
        }

        public IEnumerable<Student> GetAllStudents()
        {
            return _studentList;
        }

        public Student GetStudent(int id)
        {
            return _studentList.FirstOrDefault(e => e.Id == id);
        }

        public Student Update(Student updatedStudent)
        {
            Student student = _studentList
                .FirstOrDefault(e => e.Id == updatedStudent.Id);
            if (student != null)
            {
                student.Name = updatedStudent.Name;
                student.Email = updatedStudent.Email;
                student.Major = updatedStudent.Major;
                student.PhotoPath = updatedStudent.PhotoPath;
            }
            return student;
        }
    }