在ASP.NET Core MVC中上传图片的问题

时间:2019-07-07 10:04:12

标签: c# asp.net model-view-controller core

我正在尝试在asp.net核心MVC中上传图片,但是在尝试执行此操作时会引发以下异常。 (IOException:文件名,目录名或卷标语法不正确)

创建视图,这是一种接受员工姓名,电子邮件,部门和形象的表格。

@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>
        }

HomeController创建方法,该方法负责将图像插入wwwroot的“ images”文件夹中

[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>

整个HomeController代码

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");
        }
    }
}

2 个答案:

答案 0 :(得分:1)

在创建操作后更改中

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

收件人

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

希望这会有所帮助。

答案 1 :(得分:0)

您的代码没有错 只需更改

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

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