【问题标题】:I am trying to upload an image using ASP.NET Core 3.0 MVC我正在尝试使用 ASP.NET Core 3.0 MVC 上传图像
【发布时间】:2019-11-11 23:22:53
【问题描述】:

我正在尝试使用 ASP.NET Core 3.0 MVC 上传和保存图像,但遇到了一些问题。我可以上传图片,但它不会保存到数据库中。我一直在查看其他示例,但正在努力让它做我想做的事情。我对在 ASP.NET Core 3.0 MVC 中进行编程还是很陌生,所以我可能只是在看一些东西。

我正在寻找一个大脑更大的人,然后我的可以帮助我并告诉我哪里出了问题。

提前感谢您的帮助。

控制器:EmployeeControler

[HttpPost]
[ValidateAntiForgeryToken]
public async System.Threading.Tasks.Task<IActionResult> CreateAsync([Bind] Employee employee, IFormFile EmployeeImage)
{
        if (ModelState.IsValid)
        {
            objemployee.AddEmployee(employee);
        }

        if (EmployeeImage != null && EmployeeImage.Length > 0)
        {
            var fileName = Path.GetFileName(EmployeeImage.FileName);
            var filePath = Path.Combine(Directory.GetCurrentDirectory(), @"wwwroot\Images", fileName);

            using (var fileStream = new FileStream(filePath, FileMode.Create))
            {    
                await EmployeeImage.CopyToAsync(fileStream);
                return RedirectToAction("Index");
            }
        }

        return View(employee);
}

型号:EmployeeDataAccessLayer

// To add new employee record    
public void AddEmployee(Employee employee)
{
    using (SqlConnection con = new SqlConnection(connectionString))
    {
        SqlCommand cmd = new SqlCommand("SP_Add_Worker", con);
        cmd.CommandType = CommandType.StoredProcedure;

        cmd.Parameters.AddWithValue("@EmployeeNumber", employee.EmployeeNumber);
        cmd.Parameters.AddWithValue("@PositionTitle", employee.PositionTitle);
        cmd.Parameters.AddWithValue("@FirstName", employee.FirstName);
        cmd.Parameters.AddWithValue("@LastName", employee.LastName);
        cmd.Parameters.AddWithValue("@Dept", employee.Dept);
        cmd.Parameters.AddWithValue("@HireDate", employee.HireDate);
        cmd.Parameters.AddWithValue("@EmployeeImage", employee.EmployeeImage);

        con.Open();
        cmd.ExecuteNonQuery();
        con.Close();
    }
}

型号Employee

public class Employee
{
    [Key]
    public int ID { get; set; }

    [Required(ErrorMessage = "Clock Number is required")]
    public string EmployeeNumber { get; set; }

    [Required(ErrorMessage = "Position Title is required")]
    public string PositionTitle { get; set; }

    [Required(ErrorMessage = "First Name is required")]
    public string FirstName { get; set; }

    [Required(ErrorMessage = "Last Name is required")]
    public string LastName { get; set; }

    [Required(ErrorMessage = "Department is required")]
    public string Dept { get; set; }

    [Required(ErrorMessage = "Hire Date is required")]
    [Display(Name = "Start Date")]
    [DataType(DataType.Date)]
    [DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}", ApplyFormatInEditMode = true)]
    public DateTime? HireDate { get; set; }

    [Required(ErrorMessage = "Please choose file to upload.")]
    public string EmployeeImage { get; set; }
} 

查看Create:

@model Flexfab.Models.Employee
@{
    ViewData["Title"] = "Create";
}
<h2>Create</h2>
<h4>Employees</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>Clock Number:</label>
                @Html.TextBoxFor(model => model.EmployeeNumber, new { @class = "form-control", @placeholder = "Clock Number" })
                <span asp-validation-for="EmployeeNumber" class="text-danger"></span>
            </div>

            <div class="form-group">
                <label>Position:</label>
                @Html.TextBoxFor(model => model.PositionTitle, new { @class = "form-control", @placeholder = "Position Title" })
                <span asp-validation-for="PositionTitle" class="text-danger"></span>
            </div>

            <div class="form-group">
                <label>First Name</label>
                @Html.TextBoxFor(model => model.FirstName, new { @class = "form-control", @placeholder = "First Name" })
                <span asp-validation-for="FirstName" class="text-danger"></span>
            </div>

            <div class="form-group">
                <label>Last Name:</label>
                @Html.TextBoxFor(model => model.LastName, new { @class = "form-control", @placeholder = "Last Name" })
                <span asp-validation-for="LastName" class="text-danger"></span>
            </div>

            <div class="form-group">
                <label>Dept:</label>
                @Html.TextBoxFor(model => model.Dept, new { @class = "form-control", @placeholder = "Dept" })
                <span asp-validation-for="Dept" class="text-danger"></span>
            </div>

            <div class="form-group">
                <label>Hire Date:</label>
                @Html.TextBoxFor(model => model.HireDate, new { @class = "form-control", @placeholder = "mm/dd/yyyy" })
                <span asp-validation-for="HireDate" class="text-danger"></span>
            </div>

            <div class="form-group">
                <label>Employee Picture:</label>
                <br />
                <input type="file" id="EmployeeImage" name="EmployeeImage">
                @Html.HiddenFor(model => model.EmployeeImage, new { @class = "form-control" })
                <span asp-validation-for="EmployeeImage" class="text-danger"></span>
            </div>

            <div class="form-group">
                <input type="submit" value="Create" class="btn btn-primary" />
            </div>
        </form>
    </div>
</div>

<div>
    <a asp-action="Index">Back to List</a>
</div>
@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}

【问题讨论】:

    标签: image upload asp.net-core-mvc asp.net-core-3.0


    【解决方案1】:

    您不能在数据库中保存图像或其他类型的文件,但您只能保存文件的路径。图像将保存在文件夹wwwroot\Images 中。要检索文件,您需要先保存该文件。

    using (var fileStream = new FileStream(filePath, FileMode.Create))
    {    
         await EmployeeImage.CopyToAsync(fileStream);
         employee.EmloyeeImage = fileName.Uri.OriginalString;
         return RedirectToAction("Index");
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-03-20
      • 1970-01-01
      • 2021-03-13
      • 2010-10-17
      • 2010-11-25
      • 1970-01-01
      • 2020-01-01
      • 1970-01-01
      相关资源
      最近更新 更多