user3044300
user3044300

Reputation: 45

how to i create an imageurl link to sql database in mvc4

hi guys how to i able to insert imageurl into database? after i insert into my database , my imageurl row appears to be NULL.

    public HttpPostedFileBase ImageURL { get; set; }

my question.cshtml

<tr>
        <td  colspan="3">
            @Html.LabelFor(model => model.ImageURL)
            @Html.TextBoxFor(model => model.ImageURL, new { type = "file", id="fileupload", name="fileupload" })
            @Html.ValidationMessageFor(model => model.ImageURL)
            <img src="#" id="imgThumbnail" alt="preview" width="10%" height="15%" />
        </td>

my controller

foreach (QuestionVM0 q1 in qo)
            {

                int aID = question1.ActivityID.Value;

                string sImageURL = q1.ImageURL.ToString();



                Models.question1 questionCreate = new question1();

                questionCreate.ImageURL = sImageURL;
                db.questions1.Add(questionCreate);
                db.SaveChanges();
            }

Upvotes: 0

Views: 242

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038930

Your Entity Framework model should have a byte[] property mapped to a varbinary(max) column in your database. It appears that currently you have defined it as a string which is wrong. So:

public class question1 
{
    public byte[] ImageURL { get; set; }
    ...
}

And then read from the HttpPostedFileBase property on your view model and copy it to the byte[] property on your EF model:

foreach (QuestionVM0 q1 in qo)
{
    int aID = question1.ActivityID.Value;

    byte[] imageData = null;
    using (MemoryStream target = new MemoryStream())
    {
        q1.ImageURL.InputStream.CopyTo(target);
        imageData = target.ToArray();
    }

    Models.question1 questionCreate = new question1();
    questionCreate.ImageURL = imageData;
    db.questions1.Add(questionCreate);
    db.SaveChanges();
}

UPDATE:

It appears that you want to store only the location of the file in the database and not the file itself. In this case you should do this:

foreach (QuestionVM0 q1 in qo)
{
    int aID = question1.ActivityID.Value;

    string fileName = Path.GetFileName(q1.ImageURL.FileName);
    string path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
    q1.ImageURL.SaveAs(path);

    Models.question1 questionCreate = new question1();
    questionCreate.ImageURL = path;
    db.questions1.Add(questionCreate);
    db.SaveChanges();
}

Upvotes: 1

Related Questions