Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Upload Image in Asp.Net Core?

I want to upload image in "wwwroot/uploads/img" folder but i get error.I wrote the following code:

Create View :

@model imageuploader.Models.Employee

<form method="post" enctype="multipart/form-data" asp-controller="Employee" asp-action="Create">

<div class="form-group">
    <div class="col-md-10">
        <input asp-for="FirstName" class="form-control" />
    </div>
</div>

<div class="form-group">
    <div class="col-md-10">
        <input asp-for="LastName" Class="form-control" />
    </div>
</div>

<div class="form-group">
    <div class="col-md-10">
        <input asp-for="ImageName" type="file" Class="form-control" />
    </div>
</div>

<div class="form-group">
    <div class="col-md-10">
        <input type="submit" value="Create" />
    </div>
</div>

Model :

public class Employee
{
    [Key]
    public int ID { get; set; }
    [Required]
    public string FirstName { get; set; }
    [Required]
    public string LastName { get; set; }
    public string ImageName { get; set; }
}

Controller

    private readonly RegisterDBContext _context;
    private readonly IHostingEnvironment _appEnvironment;


    public EmployeeController(RegisterDBContext context, IHostingEnvironment appEnvironment)
    {

        _context = context;
        _appEnvironment = appEnvironment;
    }


    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Create(Employee emp)
    {
        if (ModelState.IsValid)
        {
            var files = HttpContext.Request.Form.Files;
            foreach (var Image in files)
            {
                if (Image != null && Image.Length > 0)
                {
                    var file = Image;
                    //There is an error here
                    var uploads = Path.Combine(_appEnvironment.WebRootPath, "uploads\\img");
                    if (file.Length > 0)
                    {
                        var fileName = Guid.NewGuid().ToString().Replace("-", "") + Path.GetExtension(file.FileName);
                        using (var fileStream = new FileStream(Path.Combine(uploads, fileName), FileMode.Create))
                        {
                            await file.CopyToAsync(fileStream);
                            emp.BookPic = fileName;
                        }

                    }
                }
            }
            _context.Add(emp);
            await _context.SaveChangesAsync();
            return RedirectToAction("Index");
        }
        else
        {
            var errors = ModelState.Values.SelectMany(v => v.Errors);
        }
        return View(emp);
    }

When i click on submit button i get an error (error line is marked), how can i upload image or file in Specified path?

Error:

NullReferenceException: Object reference not set to an instance of an object.

imageuploader.Controllers.EmployeeController+<Create>d__2.MoveNext() in EmployeeController.cs

                        var uploads = Path.Combine(_appEnvironmen.WebRootPath, "uploads\\img\\");

How can i upload image correctly in Specified path?

like image 401
topcool Avatar asked Nov 08 '17 17:11

topcool


People also ask

How can add image in web form in asp net?

To upload the image, click on Choose File and then browse to the image which you want to upload. Once the image is selected then the name of the image will be displayed next to the Choose File button as shown in the following screenshot.


2 Answers

I Solved it. I understood i initial bad

_appEnvironment

in Constructor. With repeated edits, all of the codes in question are currently correct.

Thanks @Shyju user.

like image 57
topcool Avatar answered Oct 21 '22 21:10

topcool


Here is how to upload an image in C# Asp.net core Web Application 2.1 MVC:

First I'm assuming you've created a model, added to db and now working in the controller.

I've created a Person model person model

For create get:

 //Get : Person Create
        public IActionResult Create()
        {
            return View();
        }

post Action (please see screen shot) create post action method

Finally the view Create View

Project Output: Here is the output of my project

like image 43
Jeff Avatar answered Oct 21 '22 19:10

Jeff