0
public ActionResult Create(Job job, HttpPostedFileBase upload)
{
    if (ModelState.IsValid)
    {
        string path = Path.Combine(Server.MapPath("~/Uploads"), upload.FileName);
     
        upload.SaveAs(path);
        job.JobImage = upload.FileName;
        db.Jobs.Add(job);
        db.SaveChanges();
        return RedirectToAction("Index");
    }

    ViewBag.CategoryId = new SelectList(db.Categories, "Id", "CategoryName", job.CategoryId);
    return View(job);
}

This is the code, What is the solution for this problem?

  1. the code of the problem of uploading a picture, I have tried several solutions but it did not work, like replacing the <<if(ModelState.IsValid)>> with if <<(upload.ContentLength > 0 )>> but it didn't work.
  2. the problem occurs from the line <<string path = Path.Combine(Server.MapPath("~/Uploads"), upload.FileName);>> I am not able to upload pictures. What should I do to fix this problem?
Jackdaw
  • 7,626
  • 5
  • 15
  • 33
MHK
  • 1
  • 1

2 Answers2

0

I think your upload.file name is the culprit here. You need to be sure your upload isn't returning a null value.

Also make sure the server path exist

And lastly, make sure to add enctype="multipart/form-data" to your form control in your view

P Dev
  • 31
  • 1
0

You are not checking null value for file that is getting uploaded. The code should be like this

public ActionResult Create(Job job, HttpPostedFileBase upload)
        {
            if (ModelState.IsValid)
            {
              if(upload!=null){

                string path = Path.Combine(Server.MapPath("~/Uploads"), upload.FileName);
             
                upload.SaveAs(path);
                job.JobImage = upload.FileName;
                db.Jobs.Add(job);
                db.SaveChanges();
}
                return RedirectToAction("Index");
            }

            ViewBag.CategoryId = new SelectList(db.Categories, "Id", "CategoryName", job.CategoryId);
            return View(job);
        }

For more information look into this link https://www.compilemode.com/2018/02/upload-images-on-server-folder-in-asp-net-mvc.html

Amit Kotha
  • 1,641
  • 1
  • 11
  • 16
  • I wrote it as you said, it stops showing the error but it is still not able to upload the image. I think because is a null value, any ideas on how to initialize it? or how to solve this problem? – MHK May 11 '21 at 04:15
  • Can you also upload the view from where this action is getting called – Amit Kotha May 11 '21 at 06:23