ASP.NET MVC 4 C#HttpPostedFileBase,如何存放档案 [英] ASP.NET MVC 4 C# HttpPostedFileBase, How do I Store File

查看:148
本文介绍了ASP.NET MVC 4 C#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; }
}}

控制器

 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>

我如何保存一个文件,如果我想将文件存储到服务器/路径文件夹和数据库中我只想要存储的路径名/串。

How do I store a file if I wanted to store the file into the server/path folder and in the database I only want to store the Path name/string.

推荐答案

您可以上传文件并保存它的URL在这样的数据库表:

you can upload file and save its url in the database table like this:

@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 assignmentFile = 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);
}

详细信息:

为了更好地理解参考 这个好文章上传文件(或文件)的ASP.NET MVC

这篇关于ASP.NET MVC 4 C#HttpPostedFileBase,如何存放档案的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆