【问题标题】:how to get an image uploaded using razor page如何使用剃刀页面上传图片
【发布时间】:2019-04-05 16:26:03
【问题描述】:

我正在尝试通过添加图像属性来更新课程模型,以便站点管理员可以上传 创建新课程或编辑现有课程时的课程图像。 这是我的课程模型。

public class Course
    {
        public int CourseID { get; set; }
        [Display(Name = "Course Code")]
        public string CourseCode { get; set; }
        [Display(Name = "Course Name")]
        public string Title { get; set; }
        public string Image { get; set; }
        public int Credits { get; set; }
        public int DepartmentID { get; set; }
        public string SmallSescription { get; set; }
        public string BigDescription { get; set; }
        [DataType(DataType.Date)]
        [Display(Name ="Date Launched")]
        public DateTime DateLaunched { get; set; }
        public Department Department { get; set; }
        public ICollection<Enrollment> Enrollments { get; set; }//many to many relationship with student
        public ICollection<CourseAssignment> CourseAssignments { get; set; }//many relationship with instructor.
    }

这是创建课程模型的剃须刀页面。

@page
@model MyNamespace.CreateModel
@{
    ViewData["Title"] = "Create Course";
}
<h2>Create Course</h2>
<div class="row">
    <div class="col-md-4">
        <form method="post" enctype="multipart/form-data">
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
          @*markup removed for simplicity*@
            <div class="form-group">
                <label asp-for="Course.Image" class="control-label"></label>
                <input  type="file" name="files" multiple class="form-control" />
            </div>

            <div class="form-group">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </form>
    </div>
</div>
<div>
    <a asp-page="Index">Back to List</a>
</div>
@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}

这是 CreateModel 的 OnPostAsync 方法,

namespace MyNamespace
{
   public class CreateModel :PageModel
    {
        //other code removed for simplicity
        [BindProperty]
        public Course Course { get; set; }

        public async Task<IActionResult> OnPostAsync()
        {
            if (!ModelState.IsValid)
            {
                return Page();
            }

            var emptyCourse = new Course();
            if (await TryUpdateModelAsync<Course>(emptyCourse, "course",   // Prefix for form value.
                 s => s.CourseCode, s => s.CourseID, s => s.DepartmentID, s => s.Title, s => s.Credits,s => s.Image))
            {
                _context.Courses.Add(emptyCourse);
                await _context.SaveChangesAsync();
            }

        //image being saved
        var files = HttpContext.Request.Form.Files;
        if (files[0] != null && files[0].Length > 0)
            {
            //save the extension name as well as images folder path inside the image proiperty of every course
            }
        else
            {
            //save a default image
            }
                return RedirectToPage("./Index");
        }  
    } 
} 

我想使用var files = HttpContext.Request.Form.Files; 获取HttpContext 中的文件,以便将图像路径保存到数据库。 但是files.Count;在没有图片上传时为零。因此代码

if (files[0] != null && files[0].Length > 0)
        {
            //save the extension name as well as images folder path inside the image proiperty of every course
        }

抛出异常。 我该如何解决这个问题?我希望 Image 属性保存课程的图像路径。 有没有更好的方法来获取通过 http 请求发送的文件?

【问题讨论】:

  • 您不应在 Razor Pages 应用程序的任何地方使用 Request.Form。您应该改为绑定到 IFormFile 属性:learnrazorpages.com/razor-pages/forms/file-upload
  • 我正在学习一个教程(在线),而讲师在另一个应用程序中使用了该技术。那么使用这种技术有什么缺点呢?为什么不应该使用它?
  • 缺点是您失去了使用 PageModel 属性所获得的所有好处,包括模型绑定和 Tag Helper 支持。

标签: razor-pages


【解决方案1】:

如果没有文件发布,files[0] 不是null。它不存在。因此会生成一个ArgumentOutOfRangeException。如果您想使用 Request.Form.Files,您应该验证 Count 的值:

if(Request.Form.Files.Count > 0)
{
    // you can safely access Request.Form.Files[0]
    //save the extension name as well as images folder path inside the image property of every course
}

【讨论】:

    猜你喜欢
    • 2017-02-21
    • 2021-03-01
    • 2018-04-24
    • 1970-01-01
    • 1970-01-01
    • 2020-01-26
    • 2019-01-11
    • 2020-04-15
    • 2020-11-06
    相关资源
    最近更新 更多