How do upload and associate an image with another

2019-09-11 12:32发布

问题:

I have a class, Event, and i want to be able to have images on the event page. I have defined the image class but am now sure how i can upload the image. I want to be able to store the image in the database.

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; }
    }

回答1:

If you want to handle file uploads you should use the HttpPostedFileBase type to represent the image and not a byte array:

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; }
}

then in your view you will use a file input:

@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>
}

and finally you will have the controller action to which the form will be posted and which will save the file:

[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
    }
    ...
}

You might also find the following blog post useful.