0

我有一个课程,事件,我希望能够在事件页面上显示图像。我已经定义了图像类,但现在确定如何上传图像。我希望能够将图像存储在数据库中。

public class Event
    {
        public int Id { get; set; }

        public string Title { get; set; }

        public string  Description { get; set; }

        public string Address { get; set; }

        public string AddressTwo { get; set; }

        public virtual Person Owner { get; set; }

        public DateTime Date { get; set; }

        public virtual Image Image { get; set; }
    }

 public class Image 
    {
        public int Id { get; set; }

        public string Name { get; set; }

        public string AlternateText { get; set; }

        public virtual string CssClass { get; set; }

        public Byte[] File { get; set; }
    }
4

1 回答 1

1

如果你想处理文件上传,你应该使用HttpPostedFileBase类型来表示图像,而不是字节数组:

public class Image 
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string AlternateText { get; set; }
    public virtual string CssClass { get; set; }
    public HttpPostedFileBase File { get; set; }
}

然后在您看来,您将使用文件输入:

@model Event
@using (Html.BeginForm(null, null, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    <div>
        @Html.LabelFor(x => x.Image.File)
        @Html.TextBox(x => x.Image.File, new { type = "file" })
    </div>
    ... some other fields
    <button type="submit">OK</button>
}

最后,您将拥有将发布表单并保存文件的控制器操作:

[HttpPost]
public ActionResult Upload(Event model)
{
    if (model.Image != null && model.Image.ContentLength > 0)
    {
        // an image was selected by the user => process and store it into the database
    }
    ...
}

您可能还会发现以下博客文章很有用。

于 2011-12-02T07:49:38.633 回答