0

Good day guys,

I am trying to upload an image to a folder and save the path URL in the database using ASP.NET MVC code first approach.

At the point of saving the URL path, it is returning Object referenced Null.

Below is the action method called when the form is been saved.

 [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create([Bind(Include = "Id,Account_Number,Title,Firstname,Othername,Surname,Phone_Number,Bank_AccountName, Bank_Fullname, img_Passport")] SavingsAccount savingsAccount, HttpPostedFileBase postedFile)
    {
        Thread.Sleep(2000);
        
        //Extract Image File Name.
        string fileName = "1000000005";

        //Set the Image File Path.
        string filePath = "~/Images/Uploads/SavingsAccount/" + fileName;

        //Save the Image File in Folder.
        postedFile.SaveAs(Server.MapPath(filePath));
        

        if (ModelState.IsValid)
        {
            savingsAccount.Account_Number = Account_No;
            savingsAccount.Account_Type = "Savings Account";
            savingsAccount.Account_Balance = 0;
            savingsAccount.Date_Opened = Convert.ToDateTime(DateTime.Now.ToString());
            savingsAccount.Opened_By = User.Identity.Name;
            savingsAccount.img_Passport = filePath; //Insert the Passport URL Path to database
            db.SavingsAccounts.Add(savingsAccount);
            db.SaveChanges();
     
            return View("DisplaySuccessMessage");
        }

        return View(savingsAccount);
    }

The Posted file is been seen as Null when I used breakpoint to check value sent.

Am i doing it the wrong way?

uthumvc
  • 157
  • 8
  • 1
    I think this is because of not adding `new { enctype = "multipart/form-data" })` parameter to `@html.BeginForm` in `view` page. Use this "@using (Html.BeginForm("Action Name", "Controller Name", FormMethod.Post, new { enctype = "multipart/form-data" }))" to create form – Abdul Haseeb Aug 24 '20 at 16:29
  • Exactly what the issue was. Thank you so much – uthumvc Aug 24 '20 at 17:10

1 Answers1

0

Use Upload files in ASP.NET Core like this article

public async Task<IActionResult> OnPostUploadAsync(List<IFormFile> files)
{
    long size = files.Sum(f => f.Length);

    foreach (var formFile in files)
    {
        if (formFile.Length > 0)
        {
            var filePath = Path.GetTempFileName();

            using (var stream = System.IO.File.Create(filePath))
            {
                await formFile.CopyToAsync(stream);
            }
        }
    }

    // Process uploaded files
    // Don't rely on or trust the FileName property without validation.

    return Ok(new { count = files.Count, size });
}
Akbar Asghari
  • 387
  • 3
  • 12