c# - ASP.NET MVC 4 C# HttpPostedFileBase,如何存储文件

标签 c# asp.net-mvc asp.net-mvc-3 asp.net-mvc-4 httppostedfilebase

型号

public partial class Assignment
{
    public Assignment()
    {
        this.CourseAvailables = new HashSet<CourseAvailable>();
    }

    public string AssignmentID { get; set; }
    public Nullable<System.DateTime> SubmissionDate { get; set; }
    public string Status { get; set; }
    public Nullable<decimal> Mark { get; set; }
    public string Comments { get; set; }
    public string FileLocation  { get; set; }
    public virtual ICollection<CourseAvailable> CourseAvailables { get; set; }
}}

Controller

 public ActionResult Create(Assignment assignment)
    {
        if (ModelState.IsValid)
        {


            db.Assignments.Add(assignment);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        return View(assignment);
    }

查看

<div class="editor-field">
    <%: Html.TextBoxFor(model => model.FileLocation, new { type="file"})%>
    <%: Html.ValidationMessageFor(model => model.FileLocation) %>
</div>

如果我想将文件存储到服务器/路径文件夹中,而在数据库中我只想存储路径名称/字符串,我该如何存储文件。

最佳答案

您可以像这样上传文件并将其 url 保存在数据库表中:

查看:

@using(Html.BeginForm("Create","Assignment",FormMethod.Post,new {enctype="multipart/form-data"}))
{
    ...
    <div class="editor-field">
        <%: Html.TextBoxFor(model => model.FileLocation, new { type="file"})%>
        <%: Html.ValidationMessageFor(model => model.FileLocation) %>
    </div>
    ...
}

行动:

[HttpPost]
public ActionResult Create(Assignment assignment)
{
    if (ModelState.IsValid)
    {
        if(Request.Files.Count > 0)
        {
            HttpPostedFileBase file = Request.Files[0];
            if (file.ContentLength > 0) 
            {
                var fileName = Path.GetFileName(file.FileName);
                assignment.FileLocation = Path.Combine(
                    Server.MapPath("~/App_Data/uploads"), fileName);
                file.SaveAs(assignment.FileLocation);
            }
            db.Assignments.Add(assignment);
            db.SaveChanges();
            return RedirectToAction("Index");
        }
    }

    return View(assignment);
}

详情:

为了更好地理解,请参阅 this good article Uploading a File (Or Files) With ASP.NET MVC

关于c# - ASP.NET MVC 4 C# HttpPostedFileBase,如何存储文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25125127/

相关文章:

c# - 更有效地构建树?

asp.net-mvc - ASP.NET MVC : Get all controllers

jQuery 模板和 Razor?

c# - 在没有代理的情况下调用网络服务

c# - 使用 Swagger 向端点添加注释

c# - 为对象添加相对于其局部轴的速度

javascript - Aurelia - 无法使用 typescript skeeton 使 asp net core 工作

c# - 使用 C# 在 ASP.NET MVC3 中进行远程文件扩展名验证?

c# - MVC 3 Razor - 如何阻止 View 引擎搜索 aspx 和 ascx 页面?

html - 如何在 MVC 3 Razor 中使用文本标签