【问题标题】:ASP.NET MVC 4 C# HttpPostedFileBase, How do I Store FileASP.NET MVC 4 C# HttpPostedFileBase,我如何存储文件
【发布时间】:2014-08-04 18:23:37
【问题描述】:

型号

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>

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

【问题讨论】:

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


    【解决方案1】:

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

    查看:

    @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# 和 MVC 来说还是新手
    • 一个或多个实体的验证失败。有关更多详细信息,请参阅“EntityValidationErrors”属性。什么会导致这个错误发生?当我插入时发生此错误;
    • db.SaveChanges();
    • 一个或多个实体的验证失败。有关更多详细信息,请参阅“EntityValidationErrors”属性。说明:执行当前 Web 请求期间发生未处理的异常。请查看堆栈跟踪以获取有关错误及其源自代码的位置的更多信息。异常详细信息:System.Data.Entity.Validation.DbEntityValidationException:一个或多个实体的验证失败。有关更多详细信息,请参阅“EntityValidationErrors”属性。源错误:
    • 很可能是某个字段是强制性的,在数据​​库中为空
    【解决方案2】:

    我是这样做的:

    查看.cs

    <div class="row">
    
        @using (Html.BeginForm("Upload", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
        {
            <input type="file" name="FileUpload" id="FileUpload" runat="server" />
            <input type="submit" value="Save" class="btn btn-default" />
        }
    
    </div>
    

    我使用的是HomeController,所以你在那里创建了Upload 函数。我还包括您如何将文件内容存储在数据库中,而不仅仅是位置,下面的代码使用了提供的Assignment 模型,但我还将展示如何将其保存到数据库中以我为表创建的模型为例,ITEM_ATCHMT

    如果您只有页面上的 FileUpload 控件并且没有使用它在视图上填充数据,则您不必传入模型并将其传回,因此此函数不会这样做,并且我的视图不使用模型 - 你的可能不同,如果在你的视图上使用,你可能希望保持模型被传入、返回。

    我设置了一次发布多个对象,所以我有一个List&lt;ViewDataUploadFilesResult&gt; 接收他们的数据,并在将每个文件及其元数据保存到数据库的过程中进行迭代。不过,您可以使用它一次只保存一个文件,因此我添加了代码并注释掉了多个文件的部分。希望它不会让任何人感到困惑 - 最后只有两种不同的方式来做同样的事情。

    HomeController.cs

        [HttpPost]
        public ActionResult Upload()
        {
            //var r = new List<ViewDataUploadFilesResult>();
            var r = new ViewDataUploadFilesResult();
            Assignment a = new Assignment();
    
            if (ModelState.IsValid)
            {
                if (Request.Files.Count > 0)
                {
                    HttpPostedFileBase file = Request.Files[0];
                    if (file.ContentLength > 0)
                    {
                        int fileSize = file.ContentLength;
                        var fileName = Path.GetFileName(file.FileName);
    
                        //You could do this to get the content -
                        //it would need a varbinary(max) field 
                        //Stream posted file into a byte array
                        byte[] fileByteArray = new byte[fileSize];
                        file.InputStream.Read(fileByteArray, 0, fileSize);
    
                        //Uploading properly formatted file to server.
                        string fileLocation = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
                        if (!Directory.Exists(Server.MapPath("~/App_Data/uploads")))
                            Directory.CreateDirectory(Server.MapPath("~/App_Data/uploads"));
                        file.SaveAs(fileLocation);
    
                        // I used a ViewModel to collect my file information
                        ViewDataUploadFilesResult r = new ViewDataUploadFilesResult();
                        r.Name = fileName;
                        r.FilePath = fileLocation;
                        r.Length = fileSize;
                        r.FileObj = file;
                        r.Content = fileByteArray;
    
                        // I provided a list so I could upload multiple files
                        // at once, but you might've just had the one item, above
                        //r.Add(new ViewDataUploadFilesResult()
                        //{
                        //    Name = fileName,
                        //    FilePath = fileLocation,
                        //    Length = fileSize,
                        //    FileObj = file,
                        //    Content = fileByteArray
                        //});
    
                        // Below is for singular ViewDataUploadFilesResult objects (uncomment the loop for multiple)
                        //for (int i = 0; i < r.Count; i++)
                        //{
                            //assignment.FileLocation = r[i].FilePath; //multiple objects need an index, [i]
                            assignment.FileLocation = r.FilePath;  //singular objects don't
                            assignment.Status = "Uploaded";
                            assignment.Comments = "Completed";
                        //}
    
                        // You also could've just not used ViewDataUploadFilesResult 
                        // at all, and just used assignment, only
                        // and just added fileSize, fileContents, etc. to it
    
                        EFModel db = new EFModel();  // this is your Entity Framework context
                        db.Assignments.Add(assignment);  //"Assignments" would be your table
                        db.SaveChanges();
    
                    }
    
                    return RedirectToAction("Index");
                    //return View("Index", r);
                }
            }
    
            return View();
        }
    

    附加模型

    ViewDataUploadFilesResult.cs

    public class ViewDataUploadFilesResult
    {
        public string Name { get; set; }
        public string FilePath { get; set; }
        public int Length { get; set; }
        public HttpPostedFileBase FileObj { get; set; }
        public byte[] Content { get; set; }
    }
    

    对我来说,不是使用整个 ViewModel,而是我的 Attachments 表的实际模型:

    public partial class ITEM_ATCHMT
    {
        [Key]
        public Guid ATCHMT_ID { get; set; }
    
        public int ITEM_ID { get; set; }
    
        [ForeignKey("ITEM_ID")]
        public virtual ITEM item { get; set; }
    
        [Required]
        [StringLength(50)]
        public string USER_NAME_DESC { get; set; }
    
        [Required]
        [StringLength(250)]
        public string FILE_NAME_TXT { get; set; }
    
        [Required]
        public byte[] FILE_CNTNT_CD { get; set; }
    
        [Required]
        [StringLength(10)]
        public string FILE_TYPE_DESC { get; set; }
    
        public DateTime CREATED_DT { get; set; }
    } 
    

    并说我想将它与这个项目相关联:

    public partial class ITEM
    {
        [Key]
        public int ITEM_ID { get; set; }
    
        [Required]
        [StringLength(50)]
        public string NAME { get; set; }
    
    }
    

    要使用 Entity Framework 保存任何数据,您只需填充该模型,然后在您的上下文中执行 .SaveChanges()

    EFModel db = new EFModel();  // this is my Entity Framework context
    ITEM item = new ITEM();
    item.NAME = "My Item";
    
    db.ITEM.Add(item);  //"ITEM" is my table and name of an EF model, "item" is the object that represents my model
    db.SaveChanges();
    

    如果ITEM_ID 设置为自动递增:

    ITEM_ATCHMT atchmt_model = new ITEM_ATCHMT();
    atchmt_model.ATCHMT_ID = Guid.NewGuid();
    atchmt_model.ITEM_ID = item.ITEM_ID // <-- this should have the ID
    atchmt_model.USER_NAME_DESC = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
    atchmt_model.FILE_CNTNT_CD = r.Content;
    atchmt_model.FILE_NAME_TXT = r.Name;
    atchmt_model.FILE_TYPE_DESC = r.Name.Split('.')[1];
    atchmt_model.CREATED_DT = DateTime.Now;
    
    db.ITEM_ATCHMT.Add(atchmt_model);  //"ITEM_ATCHMT" is my table
    db.SaveChanges();
    

    【讨论】:

      【解决方案3】:

                  List<Vozila> svaVozila = new List<Vozila>();
                  using (StreamReader sr = new StreamReader(@"C:\proba\MvcApplication1\MvcApplication1\fajlovi\vozila.txt"))
                  {
                      while (sr.Peek() >= 0)
                      {
                          string str;
                          string[] strArray;
                          str = sr.ReadLine();
      
                          strArray = str.Split('|');
                          Vozila auto = new Vozila();
                          auto.Registracija = strArray[0];
                          auto.Marka = strArray[1];
                          auto.GodinaProiz = strArray[2];
                          auto.Boja = strArray[3];
      
                          svaVozila.Add(auto);
      
      
      
      
      
                      }
                  }
                  string registracija = Request.Form["registracija"];
                  string datum = Request.Form["Datum"];
                  string odM = Request["odMesta"];
                  string doM = Request.Form["doMesta"];
                  string kilometara = Request.Form["kilometara"];
                  if (!String.IsNullOrEmpty(registracija))
                  {
                      using (StreamWriter wr = new StreamWriter(@"C:\proba\MvcApplication1\MvcApplication1\fajlovi\" + registracija + ".txt", true))
                      {
                          wr.WriteLine(registracija + "|" + datum + "|" + odM + "|" + doM + "|" + kilometara);
      
                      }
                  }
      
      
                  return View(svaVozila);
              }
              public ActionResult Prikaz()
              {
      
                  List<Vozila> svaVozila = new List<Vozila>();
                  using (StreamReader sr = new StreamReader(@"C:\proba\MvcApplication1\MvcApplication1\fajlovi\vozila.txt"))
                  {
                      while (sr.Peek() >= 0)
                      {
                          string str;
                          string[] strArray;
                          str = sr.ReadLine();
      
                          strArray = str.Split('|');
                          Vozila auto = new Vozila();
                          auto.Registracija = strArray[0];
                          auto.Marka = strArray[1];
                          auto.GodinaProiz = strArray[2];
                          auto.Boja = strArray[3];
      
                          svaVozila.Add(auto);
      
      
      
      
      
                      }
                  }
                  string reg = Request["reg"];
                  string Marka = "";
                  string godia = "";
                  int kilometri = 0;
                  for (int i = 0; i < svaVozila.Count; i++)
                  {
                      if (svaVozila[i].Registracija == reg)
                      {
                          Marka = svaVozila[i].Marka;
                          godia = svaVozila[i].GodinaProiz;
      
                      }
      
                  }
                  if (!String.IsNullOrEmpty(reg))
                  {
                      List<PredjeniPut> predj = new List<PredjeniPut>();
                      using (StreamReader sr = new StreamReader(@"C:\proba\MvcApplication1\MvcApplication1\fajlovi\" + reg + ".txt"))
                      {
                          while (sr.Peek() >= 0)
                          {
                              string str;
                              string[] strArray;
                              str = sr.ReadLine();
      
                              strArray = str.Split('|');
                              PredjeniPut put = new PredjeniPut();
                              put.Registracija = strArray[0];
                              put.Datum = strArray[1];
                              put.Odmesta = strArray[2];
                              put.Domesta = strArray[3];
                              put.Kilometara = Convert.ToInt32(strArray[4]);
      
                              predj.Add(put);
      
      
      
      
      
                          }
      
      
      
                      }
      
                      for (int i = 0; i < predj.Count; i++)
                      {
                          kilometri += predj[i].Kilometara;
      
                      }
                  }
                  ViewData["Kilometri"] = kilometri;
                  ViewData["reg"] = reg;
                  ViewData["Marka"] = Marka;
                  ViewData["godina"] = godia;
      
      
      
      
      
      
      
      
      
                  return View(svaVozila);
              }
      
          }
      }
      @*@model List<MvcApplication1.Models.Vozila>
      @{
          
          ViewBag.Title = "Index";
          
          
      }
      
      
      <h2>Index</h2>
      @using (Html.BeginForm("index,home"))
      {
         
      <select id="Select1" name="registracija">
          @foreach (var i in Model)
          {
        <option value="@i.Registracija">@i.Registracija</option>
              
          }
          </select>
          
          <br />   
          <label>Datum</label><input id="Text1" type="text"name ="datum" /> <br />
              <label>Od mesta</label><input id="Text1" type="text"name="odMesta" /><br />
             <label>Do mesta</label> <input id="Text1" type="text"name="doMesta" /><br />
             <label>Kilometara</label> <input id="Text1" type="text"name="kilometara" /><br />
       
      
      
      <input id="Submit1" type="submit" value="Prosledi" />
      }
        @Html.ActionLink("Prikaz","Prikaz","home");*@
      @*@model List<MvcApplication1.Models.Vozila>
      @{
          ViewBag.Title = "Prikaz";
      }
      
      
      <h2>Prikaz</h2>
      @using (Html.BeginForm("Prikaz,home"))
      {
      <select id="Select1" name="reg">
          @foreach (var i in Model)
          {
        <option value="@i.Registracija">@i.Registracija</option>
              
          }
          </select>
      <input id="Submit1" type="submit" value="Prikazi" />
      
      
      
          <table border="1">
              <tr>
                  <th>Registracija</th>
                  <th>GodinaProizvodnje</th>
                  <th>Marka</th>
                  <th>Kilometri</th>
                  
      
              </tr>
              <tr>
                  <td>@ViewData["reg"]</td>
                  <td>@ViewData["Godina"]</td>
                  <td>@ViewData["Marka"]</td>
                  <td>@ViewData["Kilometri"]</td>
      
      
              </tr>
      
      
          </table>
          
          
          
      }
      *@

      【讨论】:

      • 欢迎来到 SO。仅提供代码的答案解决了该问题,但如果您解释为什么这样做,它们肯定会得到改进。
      猜你喜欢
      • 1970-01-01
      • 2018-02-01
      • 2013-04-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多