简体   繁体   中英

Upload image to SQL database from ASP.NET MVC

I am trying to upload an image to a SQL database using ASP.NET MVC. The database BeforeImage remains as null although I am receiving no error a few file sizes and formats. Thanks

 public class Job
 {
    public int ID { get; set; }
    public byte[] BeforeImage { get; set; }
    public byte[] AfterImage { get; set; }
  }

View model:

public class BeforePhotoVM
{
    public int ID { get; set; }
    public HttpPostedFileBase BeforeImage { get; set; }
}

Get:

 public ActionResult AddBefore(int? id)
 {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }

        var job = db.Jobs.Find(id);
        var BeforeVM = new BeforePhotoVM();

        //vm = db.Jobs.Find(id);
        return View("Job2", BeforeVM);
}

Post:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult AddBefore([Bind(Include = "ID,BeforeImage")] BeforePhotoVM BeforeVM)
{
    var job = db.Jobs.Find(BeforeVM.ID);

    if (ModelState.IsValid)
    {
       byte[] BeforeImage = new byte[BeforeVM.BeforeImage.InputStream.Length];
       BeforeVM.BeforeImage.InputStream.Read(BeforeImage, 0, BeforeImage.Length);

       job.BeforeImage = BeforeImage;

       db.Entry(job).State = EntityState.Modified;
       db.SaveChanges();

       return RedirectToAction("AddBefore", new { id = job.ID });
    }

    return View("Job");
}

Look, you are doing too many things for something that should be simple. Plus, next time, post ur html code with ur ajax.

Let me try to help you.

At your asp.net page.

your Html.Begin form should have the enctype = "multipart/form-data"

like this

@using (Ajax.BeginForm("Here goes ur action", "Here goes ur controller", new AjaxOptions { OnSuccess = "something with sucess" }, new { enctype = "multipart/form-data" }))

with that in mind lets got to ur model

public byte[] Photo { get; set; }

ok ... now lets finish with the controller

        public ActionResult Cadastro(YOURMODEL _model, HttpPostedFileBase file)
    {
        _model.Photo = new byte[file.ContentLength];

see, ur controller recives the HttpPostedFileBase and u can access creating a new byte.. but remember.. in ur asp.net code the file name has to be the same in ur controller as it bellow

The rest is with u Hope this will help you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM