There is a breaking change in core 3.1 for the IForm class, above is Core 2.1. make sure you add asp-action="Create" enctype="multipart/form-data" to the Create View to populate the path. After that small change, It's working like a charm for me. Kudos to Venkat, you rock!!
Awesome video. Very informative, thank you! Just a quick comment: When you use the CopyTo() method from the IFormFile interface, you instantiate a new filestream object as the parameter, resulting in you not closing the filestream object. This will give SystemIO exceptions later on if you want to delete those images from the server. A simple fix is just to instantiate the filestream object before using the CopyTo() method, and thereafter calling the Close() method: FileStream fs = new FileStream(filePath, FileMode.Create); model.Image.CopyTo(fs); fs.Close();
Thank you for the pointer, alternatively you could achieve the same by doing this using(FileStream fs = new FileStream(filePath, FileMode.Create)) { model.Image.CopyTo(fs); }
You guys saved me. I was uploading an excel file using reference of this video and later while reading that file I got following error : "the process cannot access the file because it is being used by another process". After applying this help my code worked. Thank you guys. :)
***To Delete the old image when uploadin a new one:*** ***Interface: IPhotoRepository.cs:*** public interface IPhotoRepository { string GetOldUserPhoto(string userId); } Entity Class: EFPhotoRepository.cs (or you can name it as you want): public class EFPhotoRepository : IPhotoRepository { private readonly AppDbContext context; public EFPhotoRepository(AppDbContext context) { this.context = context; } public string GetOldUserPhoto(string userId) { var user = context.Users.SingleOrDefault(u => u.Id == userId); var userPhotoPath = user.PhotoPath; return userPhotoPath; } } ***Inject the IPhotoRepository to the Controller, do not forget the constructor & the private fields: *** ***(in my case i injected all services I needed):*** private readonly UserManager userManager; private readonly SignInManager signInManager; private readonly RoleManager roleManager; private readonly IHostingEnvironment hostingEnvironment; private readonly IPhotoRepository photoRepository; public AccountController(UserManager userManager, SignInManager signInManager, RoleManager roleManager, IHostingEnvironment hostingEnvironment, IPhotoRepository photoRepository) { this.userManager = userManager; this.signInManager = signInManager; this.roleManager = roleManager; this.hostingEnvironment = hostingEnvironment; this.photoRepository = photoRepository; } ***Implemet your Action*** ***(in my case the Action names "EditProfile" and the ViewModel names "EditUserProfileViewModel"):*** [HttpPost] public async Task EditProfile(EditUserProfileViewModel model) { string uniqueFileName = null; if (model.Photo != null) { string usersPhotosUploadFolder = Path.Combine(hostingEnvironment.WebRootPath, "Users Photos"); var oldPhotoName = photoRepository.GetOldUserPhoto(model.Id); string fullPath = Path.Combine(usersPhotosUploadFolder + "/" + oldPhotoName); if (System.IO.File.Exists(fullPath)) { System.IO.File.Delete(fullPath); } uniqueFileName = Guid.NewGuid().ToString() + "_" + model.Photo.FileName; string photoPath = Path.Combine(usersPhotosUploadFolder, uniqueFileName); model.Photo.CopyTo(new FileStream(photoPath, FileMode.Create)); } var user = await userManager.FindByIdAsync(model.Id); if (user == null) { ViewBag.ErrorMessage = $"User with Id: {model.Id} cannot be found"; return View("NotFound"); } else { user.Gender = model.Gender; user.Nationality = model.Nationality; user.City = model.City; user.Country = model.Country; user.PhotoPath = uniqueFileName; var result = await userManager.UpdateAsync(user); if (result.Succeeded) { return RedirectToAction("Profile", "Account", new { id = user.Id }); } foreach (var error in result.Errors) { ModelState.AddModelError("", error.Description); } return View(model); } } *//* DONT FORGET TO ADD THE IPhotoRepository and EFPhotoRepository TO Sartup.cs *//* ***This is the code:*** services.AddScoped(); ***If the annotation is helpful, don't forget to hit "like" to keep the comment up***
we can also use "col-sm-4" class wrapping div element with class "card -m-3" to restrict 3 columns in one row instead of hardcoding the style attribute with min and max-width like this :
@foreach (var Employee in Model) { var photoPath = "~/Images/" + (Employee.PhotoPath ?? "banner1.jpg");
Instead of writing inline CSS, you should have used class=row and col-md-4 as in example below. 4 + 4 + 4 = 12 -- the bootstrap 12-rows model. But, you are still my great teacher. Thank you for the videos. @foreach (var employee in Model) { var photoPath = "~/images/" + employee.PhotoPath;
very concentrated video, if other guy do this he will need five or more videos.nice and informative video thanks a lot for your efforts and accept my greetings
Excellent tutorial! Jquery script wasn't working for me initially, til i double checked it thoroughly and saw i was missing a '.' before 'custom-file-label'. Thank you very much!
Hello Venkat. Thank you very much for this video. I have a question if possible, the example you did works fine for images and other files like Visio (.vxd) for example. However, it's not working for text files. I couldn't find examples about this topic. However, it seems I need to read the text file line by line and save it. Just wanted to know your feedback on this issue. Thank you very much.
I am attempting to use the newest VS2019 and .net core versions. The tutorials are excellent, and I was able to make it all work until the "File upload in asp net core mvc" tutorial; it uses a now-deprecated IHostingEnvironment. At that point, VS recommends IWebHostEnvironment. I tried many things and could not get IWebHostEnvironment to work without errors: "Model bound complex types must not be abstract or value types and must have a parameterless constructor. Alternatively, give the 'hostingEnvironment' parameter a non-null default value.". How to make it work?
I may be using a slightly older version VS2019 and .NET core and this may be just a work around, but when I encountered that error in another tutorial I used the [obsolete] attribute above the class and it worked
Hello Danny - We used IWebHostEnvironment instead of IHostingEnvironment service in Part 16 of Razor Pages Tutorial. Hope this helps. The following page has all the videos, slides and text version in sequence. www.pragimtech.com/courses/asp-net-core-razor-pages-tutorial-for-beginners/
Instead of creating new class EmployeeCreateViewModel it's better to add to existing class Employee two properties: public string PhotoPath { get; set; } [NotMapped] public IFormFile Photo { get; set; } So with Photo property we work on View and we don't have this column in DB table Employee (by owing to the attribute NotMapped: you also must add namespace System.ComponentModel.DataAnnotations.Schema). By means of PhotoPath property we save file path in DB. What do you think?
Yes this is the best way, specially for large models. No need to repeat the whole model just for one or two fields. Great video Venkat, You are the best. Thanks Advance.
Hi Kudvenkat, great tutorial so far, thankyou for making it. Just letting you know, I had to change line 6 in Details.cshtml from var photoPath = "~/images/" + (Model.Employee.PhotoPath ?? "noimage.jpg"); } to var photoPath = "/images/" + (Model.Employee.PhotoPath ?? "noimage.jpg");
} // to allow the image to show in the details view.
Genius. What made you think of that if you don't mind my asking, Steve? I assume there is different syntax because of the @model HomeDetailsViewModel in details.cshtml but don't understand why there would be. In Django that is not an issue: you can use either one.
Hello and first: GREAT GREAT GREAT and Thanks. I started learning how to code this summer. Now Iam very haby doing all ur tutorials. The last days I got stuck right here at the end. Everything worked fine till I changed the browser. If I use Firefox, everthings works good. Just as I tryed to debugg with edge or IE the line with "uniqeFilePath" in the Create Actionmethod didnt work anymore. IO Exception . The generated path was now double in the string. BUT i found a solution! add ...GetFileName()... method like this: ..... uniqueFileName = Guid.NewGuid().ToString() + "_" + Path.GetFileName(model.Photo.FileName); ..... Hope U ca recommend this changing. Greatings from Germany
In the details view, I am not able to get the values of the model as I am getting the error of "NullReferenceException: Object reference not set to an instance of an object." how to fix this Issue?
Guys my problem solved, i forget to add "this.hostingEnvironment=hostingEnvironment" (hostingEnvironment = our host environment name). When i added this, its fixed.
When I get to 13:00 i need to create a fileName and use GetFilename and include it in a variable because filename property returns the complete path including the filename and the extension. Because of the filename appending, the final image path ends up having more than just the name appended. Am I missing something?? Here is the code change string fileName = Path.GetFileName(model.Photo.FileName); uniqueFileName = Guid.NewGuid().ToString() + "_" + fileName;
Hi, is there a way to overwrite the file or image using this method? For example, I just want to replace the image to save space on the server? Thanks in advance
Dear Venkat, In client machine, how to open a pdf document in a new browser window/new tab with highlighting a given word for search. The pdf document is in server. Is it required to have pdf reader installed in server. Same thing in case of excel , does it required MS-Excel to be installed in server in order to open a excel in the client machine. Please help .
Hi Venkat I Am getting error like NullReferenceException: Object reference not set to an instance of an object. string uploadsFolder = Path.Combine(hostingEnvironment.WebRootPath, "images"); were i went wrong please guide me
Nedd to do some changes in Homecontroller.cs for file upload. need to change from uniqueFileName = Guid.NewGuid().ToString() + "_" +model.Photo.FileName; to uniqueFileName = Guid.NewGuid().ToString() + "_" + Path.GetFileName(model.Photo.FileName); With this I dont hit any error. Thanks bro for a very helpful video.
Using .net 5, the file upload in the controller was creating an empty file (size 0), and of course the images did not display. To fix this issue, I changed the file stream / copy method to the following (which worked): string uniquePhotoFilename = null; if (model.Photo != null) { string uploadFolder = Path.Combine(_hostingEnvironment.WebRootPath, "images"); uniquePhotoFilename = $"{Guid.NewGuid()}_{model.Photo.FileName}"; //string filePath = Path.Combine(uploadFolder, uniquePhotoFilename); //model.Photo.CopyTo(new FileStream(filePath, FileMode.Create)); using (var stream = new FileStream(Path.Combine(uploadFolder, uniquePhotoFilename), FileMode.Create)) { model.Photo.CopyTo(stream); } } Thank you kudvenkat for the very informative series! Edit: I watched a few more episodes, and a modification is made to the code that implements the using statement for the file stream in part 56.
im a bit confuse , sorry and i am open to anyone could tell why, the question is , why does venkat still include the properties NAME, dept, and remove the ID instead only Photo property in the Seperate class ? what's the purpose of being inlcude in that seperate class. ? ? ? thankyou.
I created a separate view for upload and I could not get image to bind to the model's property. In Home controller, the photo property of EmployeeCreateViewModel always null.
Thanks fir the Great Video. had to tweak a little things to get the images loaded in correct path.Initially the images wasloaded, ond ebussing found that Images was not getting copied to images folder. duirng creating path : it coming like "wwwrootimages" when ideally it should come as "wwwroot\images" So just added "\\" to path between webroot and images, and also between images and uniquefilename.
An unhandled exception occurred while processing the request. IOException: The filename, directory name, or volume label syntax is incorrect : EmployeeManagment.Controllers.HomeController.Create(EmployeeCreateViewModel model) in HomeController.cs
model.Photo.CopyTo(new FileStream(filePath, FileMode.Create)); I am having a problem to upload file !!!! its showing error :model.Photo.CopyTo(new FileStream(filePath, FileMode.Create));
Hi I m binding dynamic image on img tag helper like this (). However the browset view source renders the image path but image is not showing . what i m doing mistake please help me
var stream = new FileStream(filePath, FileMode.Create); model.Photo.CopyTo(stream); stream.Dispose(); // remove all resources add this to your code, if works, put like on me
Dear Venkat, Regarding the following code, hostingEnvironment.WebRootPath provides us the absolute physical path of the wwwroot folder. I would like to ask how the physical path of the wwwroot folder looks like ??? string uploadsFolder = Path.Combine(hostingEnvironment.WebRootPath, "images");
wwwroot folder in in the root project folder. To see the physical path of the folder, simply right click on the wwwroot folder and select "Open Folder in File Explorer" from the context menu. On my machine the following is the physical path of the wwwroot folder C:\Projects\EmployeeManagement\EmployeeManagement\wwwroot Hope this answers your question.
I would like to clarify with you regarding the following code. This code will return C:\Projects\EmployeeManagement\EmployeeManagement\wwwroot\images Path.Combine(hostingEnvironment.WebRootPath, "images"); Am I correct sir ???
Hi Bashir, it's normally a space consideration. It's better to store the actual images somewhere that is optimised for large files. Also, it would help when you start having different versions of the same file eg thumbnails. Hope that helps
Hello, can you suggest me a solution for editing the information I created ? I having a problem with this when I cannot create an IFormFile variable to pass to my Edit action. I hope someone will know this !
When I publish the code and upload to the servee then image folder not shown in the publish folder. Actually i m try to upload the image using core library in web api project.
Hello AI - Yes, you have all the instructions on the following article. Hope this helps. csharp-video-tutorials.blogspot.com/2019/11/aspnet-core-mvc-course-wrap-up.html
Hi Venkat I am receiving error "Access to the path 'E:\backup\f\MyLabs\KudvenkatEmployees\EmployeeManagement\wwwroot\images' is denied", how do I resolve this? Thanks in advance
@sunilwagh I fixed it. I was making the mistake of passing just the uploadsfolderpath variable .it should have file as well. Use path.combine to combine uploadsfolder and imagefile into a variable and pass that variable to filestream.i Hope it helps.
Couldnt get the label to replace "Choose file..." with the filename with this solution so I did this instead and it works: document.querySelector('.custom-file-input').addEventListener('change', function (e) { var fileName = document.getElementById("Photo").files[0].name; var nextSibling = e.target.nextElementSibling nextSibling.innerText = fileName })
If you get null IFormFile then try to use: HttpContext.Request.Form.Files[0] it will fix your problem. I spent many hours to fix this issue. So, create a variable like this: var getImgFile = HttpContext.Request.Form.Files[0]; and instead of using model.Photo use getImgFile. My whole code: [HttpPost] public IActionResult Create(Gpu gpuData) { if (ModelState.IsValid) { var getImgFile = HttpContext.Request.Form.Files[0]; int maxId = GpuMockData.GpuCollection.Max(g => g.Id); gpuData.Id = maxId + 1; ///Check if image is null or not string uniqueImageName = null; if(getImgFile != null) { string uploadsFolder = Path.Combine(_hostingEnvironment.WebRootPath, "images"); uniqueImageName = Guid.NewGuid().ToString() + "_" + getImgFile.FileName; string filePath = Path.Combine(uploadsFolder, uniqueImageName); getImgFile.CopyTo(new FileStream(filePath, FileMode.Create)); } gpuData.Image = uniqueImageName; GpuMockData.GpuCollection.Add(gpuData); return RedirectToAction("Index", "Home"); } return View(); }
Зачем мы делаем ЭТО var photoPath = "~/images/" + (Model.Employee.PhotoPath ?? "noimage.jpg"); вместо того чтобы использовать ЭТО string filePath = Path.Combine(uploadsFolder, uniqueFileName); (из класса HomeController) ???????????????????????????? Why do we do that var photoPath = "~/images/" + (Model.Employee.PhotoPath ?? "noimage.jpg"); instead string filePath = Path.Combine(uploadsFolder, uniqueFileName); (from HomeController class)
There is a breaking change in core 3.1 for the IForm class, above is Core 2.1. make sure you add asp-action="Create" enctype="multipart/form-data" to the Create View to populate the path.
After that small change, It's working like a charm for me. Kudos to Venkat, you rock!!
Awesome video. Very informative, thank you!
Just a quick comment:
When you use the CopyTo() method from the IFormFile interface, you instantiate a new filestream object as the parameter, resulting in you not closing the filestream object. This will give SystemIO exceptions later on if you want to delete those images from the server. A simple fix is just to instantiate the filestream object before using the CopyTo() method, and thereafter calling the Close() method:
FileStream fs = new FileStream(filePath, FileMode.Create);
model.Image.CopyTo(fs);
fs.Close();
Thank you for the pointer, alternatively you could achieve the same by doing this
using(FileStream fs = new FileStream(filePath, FileMode.Create))
{
model.Image.CopyTo(fs);
}
You guys saved me. I was uploading an excel file using reference of this video and later while reading that file I got following error :
"the process cannot access the file because it is being used by another process".
After applying this help my code worked. Thank you guys. :)
Where the hell did this guy learn all this stuff from. Absolute Monster at ASP.NET Core
That's what i am wondering from very first day....And if we come to know we can also do magic.
From microsoft asp.net core documentations
***To Delete the old image when uploadin a new one:***
***Interface: IPhotoRepository.cs:***
public interface IPhotoRepository
{
string GetOldUserPhoto(string userId);
}
Entity Class: EFPhotoRepository.cs (or you can name it as you want):
public class EFPhotoRepository : IPhotoRepository
{
private readonly AppDbContext context;
public EFPhotoRepository(AppDbContext context)
{
this.context = context;
}
public string GetOldUserPhoto(string userId)
{
var user = context.Users.SingleOrDefault(u => u.Id == userId);
var userPhotoPath = user.PhotoPath;
return userPhotoPath;
}
}
***Inject the IPhotoRepository to the Controller, do not forget the constructor & the private fields: ***
***(in my case i injected all services I needed):***
private readonly UserManager userManager;
private readonly SignInManager signInManager;
private readonly RoleManager roleManager;
private readonly IHostingEnvironment hostingEnvironment;
private readonly IPhotoRepository photoRepository;
public AccountController(UserManager userManager,
SignInManager signInManager,
RoleManager roleManager,
IHostingEnvironment hostingEnvironment,
IPhotoRepository photoRepository)
{
this.userManager = userManager;
this.signInManager = signInManager;
this.roleManager = roleManager;
this.hostingEnvironment = hostingEnvironment;
this.photoRepository = photoRepository;
}
***Implemet your Action***
***(in my case the Action names "EditProfile" and the ViewModel names "EditUserProfileViewModel"):***
[HttpPost]
public async Task EditProfile(EditUserProfileViewModel model)
{
string uniqueFileName = null;
if (model.Photo != null)
{
string usersPhotosUploadFolder = Path.Combine(hostingEnvironment.WebRootPath, "Users Photos");
var oldPhotoName = photoRepository.GetOldUserPhoto(model.Id);
string fullPath = Path.Combine(usersPhotosUploadFolder + "/" + oldPhotoName);
if (System.IO.File.Exists(fullPath))
{
System.IO.File.Delete(fullPath);
}
uniqueFileName = Guid.NewGuid().ToString() + "_" + model.Photo.FileName;
string photoPath = Path.Combine(usersPhotosUploadFolder, uniqueFileName);
model.Photo.CopyTo(new FileStream(photoPath, FileMode.Create));
}
var user = await userManager.FindByIdAsync(model.Id);
if (user == null)
{
ViewBag.ErrorMessage = $"User with Id: {model.Id} cannot be found";
return View("NotFound");
}
else
{
user.Gender = model.Gender;
user.Nationality = model.Nationality;
user.City = model.City;
user.Country = model.Country;
user.PhotoPath = uniqueFileName;
var result = await userManager.UpdateAsync(user);
if (result.Succeeded)
{
return RedirectToAction("Profile", "Account", new { id = user.Id });
}
foreach (var error in result.Errors)
{
ModelState.AddModelError("", error.Description);
}
return View(model);
}
}
*//* DONT FORGET TO ADD THE IPhotoRepository and EFPhotoRepository TO Sartup.cs *//*
***This is the code:***
services.AddScoped();
***If the annotation is helpful, don't forget to hit "like" to keep the comment up***
we can also use "col-sm-4" class wrapping div element with class "card -m-3" to restrict 3 columns in one row instead of hardcoding the style attribute with min and max-width like this :
@foreach (var Employee in Model)
{
var photoPath = "~/Images/" + (Employee.PhotoPath ?? "banner1.jpg");
@Employee.Name
View
Edit
Delete
}
Instead of writing inline CSS, you should have used class=row and col-md-4 as in example below.
4 + 4 + 4 = 12 -- the bootstrap 12-rows model. But, you are still my great teacher. Thank you for the videos.
@foreach (var employee in Model)
{
var photoPath = "~/images/" + employee.PhotoPath;
@employee.Name
View
Edit
Delete
}
You're awesome! As always I love watching your contents and good explanations can mae we learn so much
very concentrated video, if other guy do this he will need five or more videos.nice and informative video thanks a lot for your efforts and accept my greetings
Excellent tutorial! Jquery script wasn't working for me initially, til i double checked it thoroughly and saw i was missing a '.' before 'custom-file-label'. Thank you very much!
احلى استااذ فينكات الله يجزيك الخير ♥
Very nice and helpful video, You are awesome!!
Thanks so much!
I really needed that in my projects, regards!
Great Success!!!!
very nice
you are the best
keep doing what u doing
barbosa will love my test
Thanks sir for your content!! Very helpful ❤
it was nice to watch your video keep doing @kudvenkat
Hello Venkat. Thank you very much for this video. I have a question if possible, the example you did works fine for images and other files like Visio (.vxd) for example. However, it's not working for text files. I couldn't find examples about this topic. However, it seems I need to read the text file line by line and save it. Just wanted to know your feedback on this issue. Thank you very much.
Just perfect
Now with Bootstrap 5 it´s not necesary to insert the script for the file name, it does by itself
++
++
Simple Amazing . Thank you so much !!!
I am attempting to use the newest VS2019 and .net core versions. The tutorials are excellent, and I was able to make it all work until the "File upload in asp net core mvc" tutorial; it uses a now-deprecated IHostingEnvironment. At that point, VS recommends IWebHostEnvironment. I tried many things and could not get IWebHostEnvironment to work without errors: "Model bound complex types must not be abstract or value types and must have a parameterless constructor. Alternatively, give the 'hostingEnvironment' parameter a non-null default value.". How to make it work?
I may be using a slightly older version VS2019 and .NET core and this may be just a work around, but when I encountered that error in another tutorial I used the [obsolete] attribute above the class and it worked
Hello Danny - We used IWebHostEnvironment instead of IHostingEnvironment service in Part 16 of Razor Pages Tutorial. Hope this helps. The following page has all the videos, slides and text version in sequence.
www.pragimtech.com/courses/asp-net-core-razor-pages-tutorial-for-beginners/
Top Professional Solutions 👍🏼
Instead of creating new class EmployeeCreateViewModel it's better to add to existing class Employee two properties:
public string PhotoPath { get; set; }
[NotMapped]
public IFormFile Photo { get; set; }
So with Photo property we work on View and we don't have this column in DB table Employee (by owing to the attribute NotMapped: you also must add namespace System.ComponentModel.DataAnnotations.Schema). By means of PhotoPath property we save file path in DB.
What do you think?
Yes this is the best way, specially for large models. No need to repeat the whole model just for one or two fields.
Great video Venkat, You are the best. Thanks Advance.
Great
Great Tutorial.
I was wondering why you did not choose the Async version for uploading photos
Thanks David
Hi Kudvenkat, great tutorial so far, thankyou for making it. Just letting you know, I had to change line 6 in Details.cshtml from var photoPath = "~/images/" + (Model.Employee.PhotoPath ?? "noimage.jpg");
} to
var photoPath = "/images/" + (Model.Employee.PhotoPath ?? "noimage.jpg");
} // to allow the image to show in the details view.
thnx man
Genius. What made you think of that if you don't mind my asking, Steve? I assume there is different syntax because of the @model HomeDetailsViewModel in details.cshtml but don't understand why there would be. In Django that is not an issue: you can use either one.
Thanks @@javaguitarist, sorry, but I can't remember, I think I might have read it someone online when researching why it didn't work.
Great job! Thank you!
Hello and first: GREAT GREAT GREAT and Thanks.
I started learning how to code this summer. Now Iam very haby doing all ur tutorials.
The last days I got stuck right here at the end. Everything worked fine till I changed the browser. If I use Firefox, everthings works good. Just as I tryed to debugg with edge or IE the line with "uniqeFilePath" in the Create Actionmethod didnt work anymore. IO Exception . The generated path was now double in the string. BUT i found a solution! add ...GetFileName()... method like this:
.....
uniqueFileName = Guid.NewGuid().ToString() + "_" + Path.GetFileName(model.Photo.FileName);
.....
Hope U ca recommend this changing.
Greatings from Germany
Dear Venkat, you have created a FileSteam object. Shouldn't we close this stream?
In the details view, I am not able to get the values of the model as I am getting the error of "NullReferenceException: Object reference not set to an instance of an object." how to fix this Issue?
I'm having the same problem, did you find a solution? Thanks in advance!
Getting the same error. Any help is appreciated.
Any Solutions?
Guys my problem solved, i forget to add "this.hostingEnvironment=hostingEnvironment" (hostingEnvironment = our host environment name). When i added this, its fixed.
When I get to 13:00 i need to create a fileName and use GetFilename and include it in a variable because filename property returns the complete path including the filename and the extension. Because of the filename appending, the final image path ends up having more than just the name appended. Am I missing something?? Here is the code change
string fileName = Path.GetFileName(model.Photo.FileName);
uniqueFileName = Guid.NewGuid().ToString() + "_" + fileName;
Yes, I had the exact same error and your recommended code fixed the issue. Thanks!
Hi, is there a way to overwrite the file or image using this method? For example, I just want to replace the image to save space on the server? Thanks in advance
Hi, venkat
thank you so much for this video it is so useful for me
how to download an uploaded image
Dear Venkat,
In client machine, how to open a pdf document in a new browser window/new tab with highlighting a given word for search. The pdf document is in server. Is it required to have pdf reader installed in server. Same thing in case of excel , does it required MS-Excel to be installed in server in order to open a excel in the client machine. Please help
.
Hi Venkat
I Am getting error like
NullReferenceException: Object reference not set to an instance of an object.
string uploadsFolder = Path.Combine(hostingEnvironment.WebRootPath, "images");
were i went wrong please guide me
have you found any solution yet? Even I am getting the same error
Which one is more efficient: To store files in DB as byte array or to store them as URL in 'wwwroot' folder?
Nedd to do some changes in Homecontroller.cs for file upload. need to change from uniqueFileName = Guid.NewGuid().ToString() + "_" +model.Photo.FileName; to uniqueFileName = Guid.NewGuid().ToString() + "_" + Path.GetFileName(model.Photo.FileName);
With this I dont hit any error.
Thanks bro for a very helpful video.
Did you see the photo that uploaded by this?
Thanks bro, its working for me
Thank you bro it worked
Sure worked this for me
Thank you Venkat.
Can you please answer why created new copy of employee? Can't we add file path to existing instance received.
Will this work if you store the images in root folder upon hosting on IIS?
I have one doubt .We are not passing the value for index view for photopath so it will always be null.
Using .net 5, the file upload in the controller was creating an empty file (size 0), and of course the images did not display. To fix this issue, I changed the file stream / copy method to the following (which worked):
string uniquePhotoFilename = null;
if (model.Photo != null)
{
string uploadFolder = Path.Combine(_hostingEnvironment.WebRootPath, "images");
uniquePhotoFilename = $"{Guid.NewGuid()}_{model.Photo.FileName}";
//string filePath = Path.Combine(uploadFolder, uniquePhotoFilename);
//model.Photo.CopyTo(new FileStream(filePath, FileMode.Create));
using (var stream = new FileStream(Path.Combine(uploadFolder, uniquePhotoFilename), FileMode.Create))
{
model.Photo.CopyTo(stream);
}
}
Thank you kudvenkat for the very informative series!
Edit: I watched a few more episodes, and a modification is made to the code that implements the using statement for the file stream in part 56.
So MVC Core performs many tasks as jquery ajax along not only just binding
im a bit confuse , sorry and i am open to anyone could tell why, the question is , why does venkat still include the properties NAME, dept, and remove the ID instead only Photo property in the Seperate class ? what's the purpose of being inlcude in that seperate class. ? ? ? thankyou.
I created a separate view for upload and I could not get image to bind to the model's property. In Home controller, the photo property of EmployeeCreateViewModel always null.
Had to dig into it.
You should add to your form in Create.cshtml:
enctype="multipart/form-data"
to make it work now.
@@Freeliner75 Thank you!!
Thanks fir the Great Video. had to tweak a little things to get the images loaded in correct path.Initially the images wasloaded, ond ebussing found that Images was not getting copied to images folder.
duirng creating path : it coming like "wwwrootimages" when ideally it should come as "wwwroot\images"
So just added "\\" to path between webroot and images, and also between images and uniquefilename.
Hello sir, I want to make Email property required on some condition only, not always. How should I proceed to achieve this?
Tank you sir!
Thank you sir..
Photo value is null on postback, (model.Photo!=null) is always false
how you have create ddl in this form that you haven't shown it.. could you explain it
Is it possible to upload via Blob Storage on Azure?
An unhandled exception occurred while processing the request.
IOException: The filename, directory name, or volume label syntax is incorrect :
EmployeeManagment.Controllers.HomeController.Create(EmployeeCreateViewModel model) in HomeController.cs
model.Photo.CopyTo(new FileStream(filePath, FileMode.Create));
I am having a problem to upload file !!!!
its showing error :model.Photo.CopyTo(new FileStream(filePath, FileMode.Create));
I get the same error :S
Hi
I m binding dynamic image on img tag helper like this ().
However the browset view source renders the image path but image is not showing . what i m doing mistake please help me
can u open the page source and click on the link. i got error that file cant be access
var stream = new FileStream(filePath, FileMode.Create);
model.Photo.CopyTo(stream);
stream.Dispose(); // remove all resources
add this to your code, if works, put like on me
@@zkop1 yes i got the file not found error when i bind dynamic image
@@zkop1 when i inspect ,its showing image path successfully bind like this
but its not generating version like this
Why is my file selection region invisible? Everything seems to work but the actual bar is invisible for some reason
Sir, can you please tell me why I am not getting WebRootPath in hostingEnvironment? I am using visual studio 2019.
use instead of
Thanks for this video. Is it possible to upload .pdf file using this way?
any kind of file dude
Dear Venkat,
Regarding the following code, hostingEnvironment.WebRootPath provides us the absolute physical path of the wwwroot folder. I would like to ask how the physical path of the wwwroot folder looks like ???
string uploadsFolder = Path.Combine(hostingEnvironment.WebRootPath, "images");
wwwroot folder in in the root project folder. To see the physical path of the folder, simply right click on the wwwroot folder and select "Open Folder in File Explorer" from the context menu.
On my machine the following is the physical path of the wwwroot folder
C:\Projects\EmployeeManagement\EmployeeManagement\wwwroot
Hope this answers your question.
I would like to clarify with you regarding the following code. This code will return C:\Projects\EmployeeManagement\EmployeeManagement\wwwroot\images
Path.Combine(hostingEnvironment.WebRootPath, "images");
Am I correct sir ???
Yes, that's correct.
This only works for the ASP.NET
2.2 version, right?
Because it doesn't work for the 3.1 version I'm working on :(
Nope. Its working for all versions
Great but how to download file?
Please make a video on uploading image to database, and displaying it on web page.
my images are in different size even if i am using the css class like you did
can someone help, please?
My images are not styling properly. Height varies and not set to 200px
same issue with me
hello friend, why not provide the sources for this video lesson?
Some of my images are being saved in the wrong orientation. Please help someone, how do I keep the original orientation?
Hello, have you found any solution for this issue?
thank you
thank you.. why don't we store the picture in the database ??
Hi Bashir, it's normally a space consideration. It's better to store the actual images somewhere that is optimised for large files. Also, it would help when you start having different versions of the same file eg thumbnails. Hope that helps
@@rolandsoftwareguy2515 thanks Roland
Hello, can you suggest me a solution for editing the information I created ? I having a problem with this when I cannot create an IFormFile variable to pass to my Edit action. I hope someone will know this !
How can we upload files to SQL Server ?
or convert IFormFile to Base64 ?
Thank you, please also make video on dataprotection provider in core
Try this.
docs.microsoft.com/en-us/aspnet/core/security/data-protection/using-data-protection?view=aspnetcore-2.2
How should I apply css? Doesnot work
When I publish the code and upload to the servee then image folder not shown in the publish folder.
Actually i m try to upload the image using core library in web api project.
enctype="multipart/form-data" ؟
Is there any place we can actually download the solution for this?
Hello AI - Yes, you have all the instructions on the following article. Hope this helps.
csharp-video-tutorials.blogspot.com/2019/11/aspnet-core-mvc-course-wrap-up.html
the dbo.Employees table doesn't show the photoPath. Anyone else having such issues?
Can you do the same vidéo, but with a database plz? i'm trying to save a file into database for cloud gaming save
where Can i find source code for the playlist ?
Hi Venkat I am receiving error "Access to the path 'E:\backup\f\MyLabs\KudvenkatEmployees\EmployeeManagement\wwwroot\images' is denied", how do I resolve this?
Thanks in advance
Even im stuck with same thing. Were you able to find a fix?
@@harishds91 No
@sunilwagh I fixed it. I was making the mistake of passing just the uploadsfolderpath variable .it should have file as well. Use path.combine to combine uploadsfolder and imagefile into a variable and pass that variable to filestream.i Hope it helps.
@@harishds91 let me try it out, thanks a lot
where the Dept came from ?
The program will crash after uploading a file using the Brave web browser. I had to switch to Chrome to make it work.
THANK YOU FOR THIS COMMENT!
I wasalso using the brave browser. I switched to Mozilla and everything worked fine. Do you know why?
Hi Sir,
Please Upload xamarin Videos
Advanced Thank you.
why didn't you created a partial class of employee instead of making a whole new class with photo prop?
ok my bad, its creating field for it in the database even its in the partial class.
what is navigation property
Couldnt get the label to replace "Choose file..." with the filename with this solution so I did this instead and it works:
document.querySelector('.custom-file-input').addEventListener('change', function (e) {
var fileName = document.getElementById("Photo").files[0].name;
var nextSibling = e.target.nextElementSibling
nextSibling.innerText = fileName
})
Where did you put that?
how about download ?
In my case, all the 3 employees are not in one row. Only 2 of them are there per row.
model.Photo is always null , why?
You must have forgot to add enctype="multipart/form-data" in form tag under create.cshtml view.
Now need to use IWebHostEnvironment instead IHostingEnvironment
If you get null IFormFile then try to use: HttpContext.Request.Form.Files[0] it will fix your problem. I spent many hours to fix this issue.
So, create a variable like this:
var getImgFile = HttpContext.Request.Form.Files[0];
and instead of using model.Photo use getImgFile.
My whole code:
[HttpPost]
public IActionResult Create(Gpu gpuData)
{
if (ModelState.IsValid)
{
var getImgFile = HttpContext.Request.Form.Files[0];
int maxId = GpuMockData.GpuCollection.Max(g => g.Id);
gpuData.Id = maxId + 1;
///Check if image is null or not
string uniqueImageName = null;
if(getImgFile != null)
{
string uploadsFolder = Path.Combine(_hostingEnvironment.WebRootPath, "images");
uniqueImageName = Guid.NewGuid().ToString() + "_" + getImgFile.FileName;
string filePath = Path.Combine(uploadsFolder, uniqueImageName);
getImgFile.CopyTo(new FileStream(filePath, FileMode.Create));
}
gpuData.Image = uniqueImageName;
GpuMockData.GpuCollection.Add(gpuData);
return RedirectToAction("Index", "Home");
}
return View();
}
nope that did not help, same issue
Sr Please Update Your Coursee
If anyone using .core 3.1 then u probably see a green squidly in Ihostingenvironment
Then use IWebHostEnvironment
I think im in love with Sara ...
Now use IWebHostEnvironmen
Yes because IHosting Environment should be removed so its better to use IWebHostEnvironment
Зачем мы делаем ЭТО
var photoPath = "~/images/" + (Model.Employee.PhotoPath ?? "noimage.jpg");
вместо того чтобы использовать ЭТО
string filePath = Path.Combine(uploadsFolder, uniqueFileName); (из класса HomeController)
????????????????????????????
Why do we do that
var photoPath = "~/images/" + (Model.Employee.PhotoPath ?? "noimage.jpg");
instead
string filePath = Path.Combine(uploadsFolder, uniqueFileName); (from HomeController class)
But you are still the BEST teacher!!!
I'll see you Bootsrap course, and CSS.
Now i am feeling bore because your tutorial no longer effective...
Because you are lazy to search for the updated code and learn.