0

Look, guys. I am trying to upload some info, but can not load file. Just check the code: View:

<form method="post" data-toggle="validator" role="form">
        <div class="not-that-right">
            <div class="form-group">
                <label for="Photo">Photo</label>
                <input type="file"
                       id="Photo"
                       name="Photo"
                       accept="image/gif, image/jpeg, image/png"
                       onchange="show(this)" />
            </div>

            <img id="onLoad"
                 src="#"
                 alt="photo is optional">
        </div>...........some another info.
</form>

Controller:

[HttpPost]
public ActionResult Create(InventorViewModel inventor)
{
    inventor.Photo = Request.Files["Photo"];
    InventorEntity onAdding = new InventorEntity()
    {
        FirstName = inventor.FirstName,
        SurName = inventor.SurName,
        DateOfBirth = inventor.DateOfBirth,
        Sex = inventor.Sex,
        HigherEducation = inventor.HigherEducation == "on" ? true : false,
        Description = inventor.Description,
        Country = uow.UserBL.GetCounryById(int.Parse(inventor.Country)),
        Photo = ImageConvertor.ConvertToBytes(inventor.Photo)
    };
    uow.UserBL.CreateInventor(onAdding);
    return RedirectToAction("Index");
}

so and when i add this model to database, the photo is NULL. Any ideas? Maybe i should change something (or everything xD)

Tieson T.
  • 20,774
  • 6
  • 77
  • 92
hopeless
  • 96
  • 10

2 Answers2

1

Try to insert the attribute enctype="multipart/form-data" in your form.

Tiago Ávila
  • 2,737
  • 1
  • 31
  • 34
0

try this

Add enctype = "multipart/form-data" to the form and change the controller code to this

 if (Request.Files.Count > 0)
 {
     var file = Request.Files[0];

     if (file != null && file.ContentLength > 0)
     {
        var fileName = Path.GetFileName(file.FileName);
        // do what you want to do
     }
 }

you can also make the file as part of the view model by adding HttpPostedFileBase. Model binder will bind the file to that property.

public HttpPostedFileBase attachment { get; set; }

Anto Subash
  • 3,140
  • 2
  • 22
  • 30