繁体   English   中英

asp.net core MVC上传图片的问题

[英]Problem in uploading image in asp.net core MVC

我正在尝试在 asp.net core 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 Create 方法,负责将图像插入到 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");
        }
    }
}

在您创建发布操作更改

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

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

希望这可以帮助。

你的代码没有错,只是改变

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM