This is my controller of uploading or adding picture in it
[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);
}
This is the model 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; }
}
This is my html page
<div >
<div >
<label >Member Image</label>
<div >
<input type="file" name="pic" accept="image/*" />
</div>
</div>
</div>
How to upload a picture in I add functionality in controller but it shows an error; I will try this thing first time and I don't not how to fix this error - I try but nothing will happen.
Image/cover folder
CodePudding user response:
"How to upload a picture in I add functionality in controller but it shows an error; I will try this thing first time and I don't not how to fix this error - I try but nothing will happen?"
First of all you should use
IFormFile photo
property to handle yourimage upload
option. So at your current design, when would you addIFormFile
property it will yell at youOnModelCreating
so you should useviewModel
here to handle that easily. here is the complete demo for you.
Your Current Model
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; }
}
Make a ViewModel Like This
public class MemberViewModel
{
public Member Member { get; set; }
public IFormFile? Photo { get; set; }
}
Note:
Reason forMemberViewModel
is when you addIFormFile
property within your existing model it will restrict you and there are an additional hassle to overcome that ratherViewMdoel
will make that easy for you.
Controller
[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 infolder
then we are taking thatimage name
andlocation
for saving intodatabase
as we haveviewModel
which is different than ourdomain model
so we are bindingview model
to ourdomain model
View
@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 >
<tr>
<th> <label asp-for="Member.Name"></label></th>
<td> <input asp-for="Member.Name" 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" >
<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" 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" 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>
Output
Hope it would guide you accordingly.
CodePudding user response:
First, you should use IFormFile for your image property like;
I didn't add any IFormFile property to my class that I add to my DbContext, I handled it by using it in a ViewModel and I used that ViewModel on my adding page as a Model, this is the important point I guess...
I keep the file path in AppSettings.json so I get them from there
This is the code how I upload the image to that file path...
This is the adding page view; (You don't have to use 'multiple' attribute if you will upload only one picture, if you will you must change image property from IFormFile to IFormFile[] )
I hope these help ! :)
CodePudding user response:
You need add an attribute
public IformFile pic{get;set;}
in your member class
And delete the bind attribute in your action,So that you could bind your member model