繁体   English   中英

使用 postgresql 上传图像 Asp.net 核心 3.1

[英]uploading image Asp.net core 3.1 with postgresql

我正在尝试在 asp .NET 核心中上传图像。 我无法上传图片。 没有错误信息。 无需上传图像即可正常工作。 有人告诉我这些代码有什么问题,而且我在 wwwroot 文件夹中有一个“上传”文件夹。 我在下面附上我的代码。

这是我的 Create.cshtml

@model  WebApplication1.ViewModels.EmployeeViewModel
@{
    ViewData["Title"] = "Create";
}

<h1>Create</h1>

<h4>Employee</h4>
<hr />
<div class="row">
    <div class="col-md-4">
        <form asp-action="Create" enctype="multipart/form-data ">

            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            <div class="form-group">
                <label asp-for="EmployeeName" class="control-label"></label>
                <input asp-for="EmployeeName" class="form-control" />
                <span asp-validation-for="EmployeeName" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="EmployeeProfile" class="control-label"></label>
                <div class="custom-file">
                    <input type="file" asp-for="EmployeeProfile" class="custom-file-input" />
                    <label class="custom-file-label" for="customFile">Choose file</label>
                </div>
                <span asp-validation-for="EmployeeProfile" class="text-danger"></span>

                @*<label asp-for="EmployeeImage" class="control-label"></label>
                    <input asp-for="EmployeeImage" class="form-control" />
                    <span asp-validation-for="EmployeeImage" class="text-danger"></span>*@
            </div>
            <div class="form-group">
                <label asp-for="DepartmentId" class="control-label"></label>
                <select asp-for="DepartmentId" class="form-control" asp-items="ViewBag.DepartmentId"></select>
            </div>

            <div class="form-group">
                <input type="submit" value="Create" class="btn btn-sm btn-primary rounded-0" />
                <a asp-action="Index" class="btn btn-sm btn-primary rounded-0">Back to List</a>

                @*<a asp-action="Index">Back to List</a>*@
            </div>
        </form>
    </div>
</div>


@section Scripts {
    <script>
        // Add the following code if you want the name of the file appear on select
        $(".custom-file-input").on("change", function () {
            var fileName = $(this).val().split("\\").pop();
            $(this).siblings(".custom-file-label").addClass("selected").html(fileName);
        });
    </script>
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}

这是我的员工控制器

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;

using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using WebApplication1.Models;
using WebApplication1.ViewModels;

namespace WebApplication1.Controllers
{
    public class EmployeesController : Controller
    {
        private readonly EmployeeDbContext _context;
        private readonly IWebHostEnvironment webHostEnvironment;

        public EmployeesController(EmployeeDbContext context, IWebHostEnvironment hostEnvironment)
        {
            _context = context;
            webHostEnvironment = hostEnvironment;
        }

        // GET: Employees
        //public async Task<IActionResult> Index()
        //{
        //    var employeeDbContext = _context.Employees.Include(e => e.Department);
        //    return View(await employeeDbContext.ToListAsync());
        //}

        public async Task<IActionResult> Index(string sortOrder, string currentFilter, string searchString, int? pageNumber)
        {
            ViewData["CurrentSort"] = sortOrder;
            ViewData["NameSortParm"] = String.IsNullOrEmpty(sortOrder) ? "name_desc" : "";

            if (searchString != null)
            {
                pageNumber = 1;
            }
            else
            {
                searchString = currentFilter;
            }
            //var employeeDbContext = _context.Employees.Include(e => e.Department);
            
            ViewData["CurrentFilter"] = searchString;
            var employee = from em in _context.Employees.Include(e => e.Department)
             select em;
            // var employee = from e in _context.Employees

            if (!String.IsNullOrEmpty(searchString))
            {
                employee = employee.Where(em => em.EmployeeName.Contains(searchString)
                                       || em.EmployeeName.Contains(searchString));
            }

            switch (sortOrder)
            {
                case "name_desc":
                    employee = employee.OrderByDescending(em => em.EmployeeName);
                    break;

                default:
                    employee = employee.OrderBy(em => em.EmployeeName);
                    break;
            }

            int pageSize = 3;
            return View(await PaginatedList<Employee>.CreateAsync(employee.AsNoTracking(), pageNumber ?? 1, pageSize));

            //return View(await _context.Departments.ToListAsync());
        }


        // GET: Employees/Details/5
        public async Task<IActionResult> Details(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var employee = await _context.Employees
                .Include(e => e.Department)
                .FirstOrDefaultAsync(m => m.Id == id);

            var EmployeeViewModel = new EmployeeViewModel()
            {
                Id = employee.Id,
                EmployeeName = employee.EmployeeName,
                DepartmentId = employee.DepartmentId,
                ExistingImage = employee.EmployeeImage
            };

            if (employee == null)
            {
                return NotFound();
            }

            return View(employee);
        }

        // GET: Employees/Create
        public IActionResult Create()
        {
            ViewData["DepartmentId"] = new SelectList(_context.Departments, "Id", "departmentName");
            return View();
        }

        // POST: Employees/Create
        // To protect from overposting attacks, enable the specific properties you want to bind to.
        // For more details, see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Create([Bind("EmployeeName,EmployeeImage,DepartmentId")] EmployeeViewModel model)
        {

            if (ModelState.IsValid)
            {

                string uniqueFileName = ProcessUploadedFile(model);
                Employee employee = new Employee
                {
                    EmployeeName = model.EmployeeName,
                    DepartmentId = model.DepartmentId,
                    EmployeeImage = uniqueFileName
                };

                _context.Add(employee);
                await _context.SaveChangesAsync();
                return RedirectToAction(nameof(Index));
            }
            ViewData["DepartmentId"] = new SelectList(_context.Departments, "Id", "departmentName", model.DepartmentId);
            return View(model);
        }

        // GET: Employees/Edit/5
        public async Task<IActionResult> Edit(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var employee = await _context.Employees.FindAsync(id);

            var EmployeeViewModel = new EmployeeViewModel()
            {
                Id = employee.Id,
                EmployeeName = employee.EmployeeName,
                DepartmentId = employee.DepartmentId,
                ExistingImage = employee.EmployeeImage
            }; if (employee == null)
            {
                return NotFound();
            }
            ViewData["DepartmentId"] = new SelectList(_context.Departments, "Id", "departmentName", employee.DepartmentId);
            return View(EmployeeViewModel);
        }

        // POST: Employees/Edit/5
        // To protect from overposting attacks, enable the specific properties you want to bind to.
        // For more details, see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Edit(int id, [Bind("Id,EmployeeName,EmployeeImage,DepartmentId")] EmployeeViewModel model)
        {
            if (id != model.Id)
            {
                return NotFound();
            }

            if (ModelState.IsValid)
            {
                var employee = await _context.Employees.FindAsync(model.Id);
                employee.EmployeeName = model.EmployeeName;
                employee.DepartmentId = model.DepartmentId;

                if (model.EmployeeProfile != null)
                {
                    if (model.ExistingImage != null)
                    {
                        string filePath = Path.Combine(webHostEnvironment.WebRootPath, "Uploads", model.ExistingImage);
                        System.IO.File.Delete(filePath);
                    }

                    employee.EmployeeImage = ProcessUploadedFile(model);
                }
                _context.Update(employee);
                await _context.SaveChangesAsync();

                //try
                //{
                //    _context.Update(model);
                //    await _context.SaveChangesAsync();
                //}
                //catch (DbUpdateConcurrencyException)
                //{
                //    if (!EmployeeExists(model.Id))
                //    {
                //        return NotFound();
                //    }
                //    else
                //    {
                //        throw;
                //    }
                //}
                return RedirectToAction(nameof(Index));
            }

            ViewData["DepartmentId"] = new SelectList(_context.Departments, "Id", "departmentName", model.DepartmentId);
            return View();
        }

        // GET: Employees/Delete/5
        public async Task<IActionResult> Delete(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var employee = await _context.Employees
                .Include(e => e.Department)
                .FirstOrDefaultAsync(m => m.Id == id);

            var EmployeeViewModel = new EmployeeViewModel()
            {
                Id = employee.Id,
                EmployeeName = employee.EmployeeName,
                DepartmentId = employee.DepartmentId,
                ExistingImage = employee.EmployeeImage
            };


            if (employee == null)
            {
                return NotFound();
            }

            return View(EmployeeViewModel);
        }

        // POST: Employees/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> DeleteConfirmed(int id)
        {
            var employee = await _context.Employees.FindAsync(id);
            var CurrentImage = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot\\Uploads", employee.EmployeeImage);
            _context.Employees.Remove(employee);

            if (await _context.SaveChangesAsync() > 0)
            {
                if (System.IO.File.Exists(CurrentImage))
                {
                    System.IO.File.Delete(CurrentImage);
                }
            }

            return RedirectToAction(nameof(Index));
        }

        private bool EmployeeExists(int id)
        {
            return _context.Employees.Any(e => e.Id == id);
        }

        private string ProcessUploadedFile(EmployeeViewModel model)
        {
            string uniqueFileName = null;
            

            if (model.EmployeeProfile != null)
            {
                string uploadsFolder = Path.Combine(webHostEnvironment.WebRootPath, "Uploads");
           //     uniqueFileName = Guid.NewGuid().ToString() + "_" + model.EmployeeProfile.FileName;
                uniqueFileName = Guid.NewGuid().ToString() + "_" + Path.GetFileName(model.EmployeeProfile.FileName);
                string filePath = Path.Combine(uploadsFolder, uniqueFileName);
                using (var fileStream = new FileStream(filePath, FileMode.Create))
                {
                    model.EmployeeProfile.CopyTo(fileStream);
                }


            }

            return uniqueFileName;
        }
    }
}

这是 ProcessUploadedFile 方法

 private string ProcessUploadedFile(EmployeeViewModel model)
        {
            string uniqueFileName = null;
            

            if (model.EmployeeProfile != null)
            {
                string uploadsFolder = Path.Combine(webHostEnvironment.WebRootPath, "Uploads");
           //     uniqueFileName = Guid.NewGuid().ToString() + "_" + model.EmployeeProfile.FileName;
                uniqueFileName = Guid.NewGuid().ToString() + "_" + Path.GetFileName(model.EmployeeProfile.FileName);
                string filePath = Path.Combine(uploadsFolder, uniqueFileName);
                using (var fileStream = new FileStream(filePath, FileMode.Create))
                {
                    model.EmployeeProfile.CopyTo(fileStream);
                }


            }

            return uniqueFileName;
        }

我有 3 个视图模型,见下文 EmployeeViewModel EditImageViewModel UploadImageViewModel

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
using WebApplication1.Models;
using WebApplication1.ViewModels;

namespace WebApplication1.ViewModels
{

    public class EmployeeViewModel : EditImageViewModel
    {
        [Required(ErrorMessage = "Please enter Employee Name")]
        public string EmployeeName { get; set; }


        // Navigation Properties
        public int? DepartmentId { get; set; }
        public Department Department { get; set; }

    }
}



using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace WebApplication1.ViewModels
{
    public class EditImageViewModel : UploadImageViewModel
    {
        public int Id { get; set; }
        public string ExistingImage { get; set; }

    }
}

using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;

namespace WebApplication1.ViewModels
{
    public class UploadImageViewModel
    {
        [Required(ErrorMessage = "Please choose profile image")]
        [Display(Name = "Profile Picture")]
        public IFormFile EmployeeProfile { get; set; }

    }
}

您已注释掉 EmployeeImage,您只将 EmployeeProfile 传递给操作,但是

您没有绑定 EmployeeProfile

改成这样:

[HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Create([Bind("EmployeeName,EmployeeProfile,//***others")] EmployeeViewModel model)

然后我可以使用您的代码上传文件。

[Bind]指定 model 的哪些属性应包含在 model 绑定中。检查:

https://docs.microsoft.com/en-us/aspnet/core/mvc/models/model-binding?view=aspnetcore-5.0#bind-attribute

整个代码:

        [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Create([Bind("EmployeeName,EmployeeProfile")] EmployeeViewModel model)
    {

        if (ModelState.IsValid)
        {

            string uniqueFileName = ProcessUploadedFile(model);
            Employee employee = new Employee
            {
                EmployeeName = model.EmployeeName,
                EmployeeImage = uniqueFileName
            };
            _context.Add(employee);
            await _context.SaveChangesAsync();
            return RedirectToAction(nameof(Index));
        }

        return RedirectToAction("Index");
    }
   

    private string ProcessUploadedFile(EmployeeViewModel model)
    {
        string uniqueFileName = null;

        if (model.EmployeeProfile != null)
        {
            string uploadsFolder = Path.Combine(webHostEnvironment.WebRootPath, "Uploads");
            //     uniqueFileName = Guid.NewGuid().ToString() + "_" + model.EmployeeProfile.FileName;
            uniqueFileName = Guid.NewGuid().ToString() + "_" + Path.GetFileName(model.EmployeeProfile.FileName);
            string filePath = Path.Combine(uploadsFolder, uniqueFileName);
            using (var fileStream = new FileStream(filePath, FileMode.Create))
            {
                model.EmployeeProfile.CopyTo(fileStream);
            }
        }
        return uniqueFileName;
    }

创建.cshtml:

<div class="row">
<div class="col-md-4">
    <form asp-action="Create" enctype="multipart/form-data">

        <div asp-validation-summary="ModelOnly" class="text-danger"></div>
        <div class="form-group">
            <label asp-for="EmployeeName" class="control-label"></label>
            <input asp-for="EmployeeName" class="form-control" />
            <span asp-validation-for="EmployeeName" class="text-danger"></span>
        </div>
        <div class="form-group">
            <label asp-for="EmployeeProfile" class="control-label"></label>
            <div class="custom-file">
                <input type="file" asp-for="EmployeeProfile" class="custom-file-input" />
                <label class="custom-file-label" for="customFile">Choose file</label>
            </div>
            <span asp-validation-for="EmployeeProfile" class="text-danger"></span>
        </div>

        <div class="form-group">
            <input type="submit" value="Create" class="btn btn-sm btn-primary rounded-0" />
            <a asp-action="Index" class="btn btn-sm btn-primary rounded-0">Back to List</a>

        </div>
    </form>
</div>

Model:

public class Employee
{
    [Key]
    public int Id { get; set; }
    public string EmployeeName { get; set; }
    public string EmployeeImage { get; set; }
}

public class EmployeeViewModel
{
    public int Id { get; set; }
    public string EmployeeName { get; set; }    
    public string LastName { get; set; }
    [NotMapped]
    public IFormFile EmployeeProfile { get; set; }
}

结果:

在此处输入图像描述

暂无
暂无

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

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