如何使用剃须刀页面上传图像

时间:2018-11-01 12:36:45

标签: razor-pages

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

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请求发送的文件?

1 个答案:

答案 0 :(得分:0)

如果未发布任何文件,则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
}