【问题标题】:How to upload files in an Asp.net MVC 5 application如何在 Asp.net MVC 5 应用程序中上传文件
【发布时间】:2016-12-08 12:39:30
【问题描述】:

我正在尝试在我的应用程序中上传文件。我在我的模型中使用了HttpPostedFileBase 和一个byte[] 数组,但不知道为什么在我运行我的应用程序时会显示此错误。下面我还上传了运行应用程序时显示的错误的image

显示的错误是:

在模型生成过程中检测到一个或多个验证错误:

AdSite.Models.HttpPostedFileBase: : EntityType 'HttpPostedFileBase' has no key defined. Define the key for this EntityType. HttpPostedFileBases: EntityType: EntitySet 'HttpPostedFileBases' 基于没有定义键的类型'HttpPostedFileBase'。`

我的模特:

public class Album
{
    [Key]
    public int Id { get; set; }
    public string ProductTitle { get; set; }
    public string Description { get; set; }
    public string ImageFileName { get; set; }
    public int ImageSize { get; set; }
    public byte[] ImageData { get; set; }
    [Required(ErrorMessage="Please select image file.")]
    public HttpPostedFileBase File { get; set; }        
}

我的控制器代码:

public ActionResult Upload([Bind(Include = "Id,ProductTitle,Description,ImageFileName,ImageData,File,ImageSize")]Album album)
{
    if (ModelState.IsValid)
    {
        //  album.ImageFileName = album.File.FileName;
        // album.ImageSize = album.File.ContentLength;

        byte[] data = new byte[album.File.InputStream.Length];
        album.File.InputStream.Read(data, 0, data.Length);
        album.ImageData = data;

        var db = new AlbumContext();
        db.Albums.Add(album);
        db.SaveChanges();

        return RedirectToAction("Index");
    }
    return View(album);
}

我的查看代码:

<div class="form-group">
    <label class="control-label col-md-2">Select Image:</label> 
    <div class="col-md-10">
        @Html.TextBoxFor(model=>model.File, new { type="file"})
        @Html.ValidationMessage("CustomError")
    </div>
</div>

【问题讨论】:

  • 在“绑定”属性中,您可以定义“专辑”的属性。 'File' 属性从何而来?
  • 您好@SRQCoder,File 属性在Model class 中定义。它的类型为HttpPostedFileBase File。你可以在这里看到我的模型类。
  • 您需要从数据模型中删除public HttpPostedFileBase File { get; set; }(它是一个复杂的对象,不能存储在数据库列中)。您编辑数据,所以使用视图模型,视图模型将包含该属性(而不是 public byte[] ImageData { get; set; } 属性 - What is ViewModel in MVC?

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


【解决方案1】:

这就是您要使用模型检索数据然后将其转换为您的 DTO 对象的原因。

错误是因为您试图将System.Web.HttpPostedFileBase 类存储到您的数据库中。这不是您要控制的类,也不是为了直接存储在数据库中而创建的。在这种情况下,HttpPostedFileBase 是您的“模型”。

创建另一个对象并将其绑定到您的DbContext 以将您需要的关于该文件的内容存储在数据库中。不要只是把物体扔在那里。

【讨论】:

  • 谢谢。但是你能在这里给我看一个示例代码吗?
  • 您的意思是为需要上传的文件的其他信息创建一个新的“模型类”吗?那就是我需要两个类,一个用于 HttpPostedFileBase 属性,一个用于另一个属性??
  • 我的意思是为 HttpPostedFileBase 提供的任何信息创建一个 DTO 类。
  • 我提供了HttpPostedFileBase 课程的链接。您已经有了 Album 课程,只需对您的文件执行类似的过程。
  • @krillgar 你能帮忙解决这个问题吗question
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-09
相关资源
最近更新 更多