Hassan
Hassan

Reputation: 21

Problem in uploading image in asp.net core MVC

I am trying to upload image in asp.net core MVC but the following exception is thrown while trying to do that. (IOException: The filename, directory name, or volume label syntax is incorrect)

The Create View, which is a form that accept the name,email,department and image of an employee.

@model  EmployeeCreateViewModel
@{ 
    ViewBag.Title = "Create Employee";
}
    <form enctype="multipart/form-data" asp-controller="Home" asp-action="Create" method="post" class="mt-3">
        <div class="form-group row">
            <label asp-for="Name" class="col-sm-2 col-form-label"></label>
            <div class="col-sm-10">
                <input asp-for="Name" class="form-control" placeholder="Name" />
                <span asp-validation-for="Name" class="text-danger"></span>
            </div>
        </div>

        <div class="form-group row">
            <label asp-for="Email" class="col-sm-2 col-form-label"></label>
            <div class="col-sm-10">
                <input asp-for="Email" class="form-control" placeholder="Email" />
                <span asp-validation-for="Email" class="text-danger"></span>
            </div>
        </div>

        <div class="form-group row">
            <label asp-for="Department" class="col-sm-2 col-form-label"></label>
            <div class="col-sm-10">
                <select asp-for="Department" class="custom-select mr-sm-2" asp-items="Html.GetEnumSelectList<Dept>()"></select>
                <span asp-validation-for="Department" class="text-danger"></span>
            </div>
        </div>

        <div class="form-group row">
            <label asp-for="Photo" class="col-sm-2 col-form-label"></label>
            <div class="col-sm-10">
                <div class="custom-file">
               <input asp-for="Photo" class="form-control custom-file-input"/>
    <label class="custom-file-label">Choose file...</label>
</div>

            </div>
        </div>

        <div class="form-group row">
            <div class="col-sm-10">
                <button type="submit" class="btn btn-primary">Create</button>
            </div>
        </div>


        @section  Scripts
        {
        <script>
            $(document).ready(function () {

                $('.custom-file-input').on("change", function () {
                    var fileName = $(this).val().split("\\").pop();
                    $(this).next('.custom-file-label').html(fileName);
                });
            });
        </script>
        }

The HomeController Create Method which is responsible for inserting the image in the "images" folder in wwwroot

[HttpPost]
        public IActionResult Create (EmployeeCreateViewModel model)
        {
            if(ModelState.IsValid)
            {
                string uniqueFileName=null;
                if(model.Photo != null)
                {
                  string uploadsFolder =  Path.Combine(hostingEnvironment.WebRootPath, "images");
                 uniqueFileName =   Guid.NewGuid().ToString() + "_" + model.Photo.FileName;
                 string filePath = Path.Combine(uploadsFolder, uniqueFileName);
                    model.Photo.CopyTo(new FileStream(filePath, FileMode.Create));

                }
                Employee newEmployee = new Employee
                {

                    Name = model.Name,
                    Email = model.Email,
                    Department = model.Department,
                    PhotoPath = uniqueFileName

                };

                _employeeRepository.Add(newEmployee);
                return RedirectToAction("Details", new { id = newEmployee.Id });
            }

            return View();
        }


</form>

The Whole HomeController Code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using EmployeeManagement.Models;
using EmployeeManagement.ViewModels;
using Microsoft.AspNetCore.Hosting;
using System.IO;

namespace EmployeeManagement.Controllers
{
    public class HomeController : Controller
    {
        private readonly IEmployeeRepository _employeeRepository;
        private readonly IHostingEnvironment hostingEnvironment;


        public HomeController(IEmployeeRepository employeeRepository, IHostingEnvironment hostingEnivironment)
        {
            _employeeRepository = employeeRepository;
            this.hostingEnvironment = hostingEnivironment;

        }
        public ViewResult Index()
        {
            var model = _employeeRepository.GetAllEmployees();
            return View(model);
        }

        public ViewResult Details(int id)
        {
            HomeDetailsViewModel homeDetailsViewModel = new HomeDetailsViewModel() {

                Employee = _employeeRepository.GetEmployee(id),
                PageTitle = "Employee Details"
            };
            return View(homeDetailsViewModel);

        }

        [HttpGet]
        public ViewResult Create ()
        {
            return View();
        }

        [HttpPost]
        public IActionResult Create (EmployeeCreateViewModel model)
        {
            if(ModelState.IsValid)
            {
                string uniqueFileName=null;
                if(model.Photo != null)
                {
                  string uploadsFolder =  Path.Combine(hostingEnvironment.WebRootPath, "images");
                 uniqueFileName =   Guid.NewGuid().ToString() + "_" + model.Photo.FileName;
                 string filePath = Path.Combine(uploadsFolder, uniqueFileName);
                    model.Photo.CopyTo(new FileStream(filePath, FileMode.Create));

                }
                Employee newEmployee = new Employee
                {

                    Name = model.Name,
                    Email = model.Email,
                    Department = model.Department,
                    PhotoPath = uniqueFileName

                };

                _employeeRepository.Add(newEmployee);
                return RedirectToAction("Details", new { id = newEmployee.Id });
            }

            return View();
        }

        public IActionResult Delete(Employee employee)
        {
            _employeeRepository.Delete(employee.Id);
            return RedirectToAction("Index");
        }

        public ViewResult Edit(Employee employeeEdited)
        {

            return View();


        }

        public IActionResult Update(Employee employeechanged)
        {
            _employeeRepository.Update(employeechanged);
            return RedirectToAction("Index");
        }
    }
}

Upvotes: 1

Views: 1184

Answers (2)

Himanshu Pant
Himanshu Pant

Reputation: 928

In your create post action change

uniqueFileName = Guid.NewGuid().ToString() + "_" + model.Photo.FileName;

To

uniqueFileName = Guid.NewGuid().ToString() + "_" + Path.GetFileName(model.Photo.FileName);

Hope this helps.

Upvotes: 1

M.Ali El-Sayed
M.Ali El-Sayed

Reputation: 1779

Nothing wrong with your code just change

<input asp-for="Photo" class="form-control custom-file-input"/>

to

<input type="file" asp-for="Photo" class="form-control custom-file-input"/>

Upvotes: 0

Related Questions