在模型 ASP.NET CORE 中上传图片

Upload pic in Model ASP.NET CORE

这是我上传或添加图片的控制器

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("MemberId,Name,Gender,DOB,MaritalStatus,Address,PhoneNo,Skills,Hobbies,JobTitle,Technology")] Member member)
{
        if (ModelState.IsValid)
        {
            if(member.ImageName != null)
            {
                string folder = "ImageName/Cover";
                folder += member.ImageName.FileName + Guid.NewGuid().ToString();
                string serverFolder =Path.Combine(_webHostEnviroment.WebRootPath, folder);
            }

            _context.Add(member);
            await _context.SaveChangesAsync();

            return RedirectToAction(nameof(Index));
        }

        return View(member);
}

这是模型 class:

public class Member
{
    public int MemberId { get; set; }
    [StringLength(60, MinimumLength = 3)]

    public string? Name { get; set; }

    public string? Gender { get; set; }
    public DateTime DOB { get; set; }

    public string? MaritalStatus { get; set; }

    public string? Address { get; set; }

    public long PhoneNo { get; set; }

    public string? Skills { get; set; }
    public string? Hobbies { get; set; }

    public string? JobTitle { get; set; }

    public string? Technology { get; set; }

    public string? ImageName { get; set; }

    public Team? Team { get; set; }
    public ICollection<TeamMember>? TeamMembers { get; set; }
    public ICollection<ProjectMember>? ProjectMembers { get; set; }
}

这是我的 html 页面

<div class="row">
   <div class="form-group col-md-4">
       <label class="col-md-2 control-label">Member Image</label>
         <div class="col-md-10">
           <input class="form-control" type="file" name="pic" accept="image/*" />
         </div>
    </div>
</div>

如何上传图片 我在控制器中添加了功能但显示错误;我会第一次尝试这个东西,我不知道如何修复这个错误 - 我尝试了,但没有任何反应。

Image/cover 文件夹

您需要添加一个属性

public IformFile pic{get;set;} 

在您的会员中class

并删除你的action中的bind属性,这样你就可以绑定你的成员模型了

首先,您应该为图像使用 IFormFile 属性 like;

我没有将任何 IFormFile 属性 添加到我添加到我的 DbContext 的 class 中,我通过在 ViewModel 中使用它来处理它,并且我在我的添加页面上使用了该 ViewModel 作为一个模型,我猜这是重点...

我将文件路径保存在 AppSettings.json 中,所以我可以从那里获取它们

这是我将图像上传到该文件路径的代码...

这是增加的浏览量; (如果你只上传一张图片,你不必使用 'multiple' 属性,如果你愿意,你必须将图像 属性 从 IFormFile 更改为 IFormFile[] )

希望这些对您有所帮助! :)

“如何在我在控制器中添加功能时上传图片,但它显示错误;我会第一次尝试这个东西,但我不知道如何解决这个错误 - 我尝试了但是什么都不会发生吗?"

First of all you should use IFormFile photo property to handle your image upload option. So at your current design, when would you add IFormFile property it will yell at you OnModelCreating so you should use viewModel here to handle that easily. here is the complete demo for you.

您当前的型号

public class Member
    {
        [Key]
        public int MemberId { get; set; }
        [StringLength(60, MinimumLength = 3)]

        public string? Name { get; set; }

        public string? Gender { get; set; }
        public DateTime DOB { get; set; }

        public string? ImageName { get; set; }
       
       
    }

像这样制作 ViewModel

public class MemberViewModel
    {
        public Member Member { get; set; }
        public IFormFile? Photo { get; set; }
    }

Note: Reason for MemberViewModel is when you add IFormFile property within your existing model it will restrict you and there are an additional hassle to overcome that rather ViewMdoel will make that easy for you.

控制器

        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> CreateMember(MemberViewModel model, IFormFile photo)
        {
            if (photo == null || photo.Length == 0)
            {
                return Content("File not selected");
            }
            var path = Path.Combine(_environment.WebRootPath, "ImageName/Cover", photo.FileName);
            using (FileStream stream = new FileStream(path, FileMode.Create))
            {
                await photo.CopyToAsync(stream);
                stream.Close();
            }

            model.Member.ImageName = photo.FileName;

            if (model != null)
            {
                var member = new Member
                {
                    Name = model.Member.Name,
                    Gender = model.Member.Gender,
                    DOB = model.Member.DOB,
                    ImageName = model.Member.ImageName,
                    ImageLocation = path,
                };
                _context.Add(member);
                await _context.SaveChangesAsync();
            }
            return RedirectToAction("MemberList");

        }

Note: Point to remember here, firstly we are saving the image in folder then we are taking that image name and location for saving into database as we have viewModel which is different than our domain model so we are binding view model to our domain model

查看

@model DotNet6MVCWebApp.Models.MemberViewModel
<div>
    <form asp-action="CreateMember" method="post" enctype="multipart/form-data">
        <div asp-validation-summary="ModelOnly"></div><input type="hidden" asp-for="Member.MemberId" />
        <div>
            <h4><strong>Member Details</strong> </h4>

            <table class="table table-sm table-bordered table-striped">

                <tr>
                    <th> <label asp-for="Member.Name"></label></th>
                    <td> <input asp-for="Member.Name" class="form-control" placeholder="Enter member name" /><span asp-validation-for="Member.Name"></span></td>
                </tr>
                <tr>
                    <th> <label asp-for="Member.Gender"></label></th>
               
                    <td>
                        <select asp-for="Member.Gender" class="form-control">
                            <option value="Male">Male</option>
                            <option value="Female">Female</option>
                        </select>
                    <span asp-validation-for="Member.Gender"></span>
                
                </td>
                </tr>
                <tr>
                    <th> <label asp-for="Member.DOB"></label></th>
                    <td> <input asp-for="Member.DOB" class="form-control" placeholder="Enter animal category" /><span asp-validation-for="Member.DOB"></span></td>
                </tr>
                <tr>
                    <th> <label asp-for="Photo"></label></th>
                    <td>
                         <strong>Upload New File</strong> <div id="chooseFile"><input type="file" name="photo"  accept="image/*" /></div>

                    </td>
                </tr>
                <tr>
                    <th>  <button type="submit" class="btn btn-primary" style="width:107px">Save Info</button></th>
                    <td> </td>
                </tr>
                <tr>
                    <th>@Html.ActionLink("Back To List", "MemberList", new { /* id=item.PrimaryKey */ }, new { @class = "btn btn-success" })</th>
                    <td> </td>
                </tr>
            </table>
        </div>
    </form>

</div>

输出

希望它能为您提供相应的指导。