Hey! Very cool video! I just have a follow-up question: How do you do Multiple File Upload with Models? For example, if I want to save multiple files in the model, I know you change the IFormFile to a List in the model, but what else changes? Thanks a lot!
I wanna use IFormFile or FormFile method in asp.net mvc too. Can we use it? HttpPostedFileBase is easy but I wanna use only one class for upload images and FormFile seems cool.
Thank you very much for the nice video, I've couple question what is the maximum size for the upload? if you want to upload 10gb files what would be the best approach?
Thank you! Maximum size of upload for IIS is 28MB, you can change this. Please read the docs docs.microsoft.com/en-us/aspnet/core/mvc/models/file-uploads?view=aspnetcore-3.0#troubleshooting
@@RawCoding Files bigger than 1GB normally require MultiReader Filestreaming instead of IFormFile, otherwise it will just crash with Error 404 due to memory restrictions. docs.microsoft.com/de-de/aspnet/core/mvc/models/file-uploads?view=aspnetcore-5.0#upload-large-files-with-streaming Great tutorials anyways!
Watched the 7 first minutes to get started. Now I has a system that takes the uploaded image. Computes its SHA256 hash and use it as a filename. Writes the copy of the file into a subfolder. Works fairly well, but I have 2 issues. Folder should exist prior to writing file. Kinda makes sense from a technical PoV but on the other hand it would be nice if the proper folder is created if needs be. Actually this is Path.Combine that throws the exception because the path which is combined does not exist. So I shall combine the path on its own line in a try/catch and create the folder if needed. Second issue is I wonder how I should refactor this so that it is clean and reusable amongst my webapp. Creating a service ? I'll probably watch the rest of the video later. Thanks for the help.
Sorry for the late response - you should store files in cloud storage really, having a service for that makes the most sense. I have some videos in my Tricking Library series on that, the project source code is freely available as well.
Ахаха чувак ты прям осветил все темы которые мне нужны для дипломной )) респект тебе и уважуха. Кстати один вопрос, я четкого ответа нигде не получил, как лучше хранить музыкальные файлы формата mp3 в базе данных как битовый массив или в файловой системе ?
Спасибо, и удачки на задаче. Мп3 от других файлов сильно не отличаются. Если сохронять как файл то придётся стримить как страничка загрузится. Если как бити то их можна в base64 прям в src кидать или тоже стримить но больше памяти и ресурсов занимать в DB будет. Тоже blob дешевле DB. Я предпочитаю сохронять файли на диск. Если будешь сохронять в DB то делай для них отдельную таблицу id, bytes.
Great tutorial! I have a question regarding the path for axios.post("/Home/SingleFile", formData). Can I ask you how did the path become "/Home/SingleFile"? Is it "/`controllerName`/`IActionResult name`"? Somehow the path is not working, and console throws an error of 400 :(
Yes the way you think about the path is correct. 400 means there is an error, if you don't hit the back end at all and you are using dotnet core 3 you'll have to submit an intiforgery token too.
@@yoonvak Here's the solution to the issue. stackoverflow.com/a/47633056/5784635 Use @Html.AntiForgeryToken() to generate the anti forgery token and then add it to your request as a __RequestVerificationToken on the request
@@RawCoding Thank you so much! i have a extra question regarding the solution, should I create a new class with the "HttpContextExtensions"? Or can I just add that in the controller where I have the "singleFile" function in it?
Thanks for sharing this video. This is a lot clearer video tutorial for uploading a file in ASP.NET core than other video tutorial. Nice and clean! Thanks again! By the way, what if i'll be uploading a doc and pdf file? And how to show the uploaded files in the view page? I hope you could help me out on this. Thanks again!
Hey there just to clarify you want to know how to display the contents of these files on the page? Or do you mean list the files that you have uploaded and perhaps download them?
@@RawCoding Hi there! Sorry can't make replies the past days. Yes, I also wanted to download it by users if possible. So the files can be displayed in list and can be downloaded also if possible. Many thanks raw coding 😊
@@RawCoding I need this because currently I'm making a project in our school where they can upload documents in the database and they can also download it when they need. It's more of a document manager where they can sort there documents or search it rather than having it to folders and many subfolders. Sorry if I make confusions but hoping that you could help me. I'm really stuck on this part. Thanks again.
@@RawCoding I agree. I have been looking and have come up short. The best workaround I have found so far is to use get('key') or get('key') from the console. I have also incorporated a check in my JS function call to ensure the value is there. I'm doing all of this because I am running into an issue with .netcore 3 is closing the connection. I am using the JS fetch API. Any idea's on what closes connections or how to debug the issue prior to reaching the API controller?
Hello ppl! One doubt, if I am to implement this functionality in my online shop "create product" admin section, I would have to wrap the "add new product" section into a form then do a post with all the product details from name, description etc to imageFile right? I mean its the best option given the shop implementation isn't it? and then do the appropiate ammenments into the CreateProduct controller action as you are doing in this video. Then in the index page where the products are being displayed, just select the imageFile prop in product.ImageFile for example in order to display that product image. Am I going in the right direction?
Sorry, I am having some problems on making this work. The form from the view doesn't reach the parameter in the SingleFile action. It says that it's an unused parameter even though it has the same name
@@RawCoding I tried and it comes with "HTTP Error 500.31 - ANCM Failed to Find Native Dependencies" must be because of the version Edit: Managed to make it work! Thank youu!!!
No, you’ll need to add a setting in Progam.cs if you host on IIS you’ll need a setting in your webconfig, if Linux you’ll need to add a setting to your nginx config
@@RawCoding Brother, 1. multiple attachment exists (Hints: foreach (var file in files) ) 2. This is a part of a code. save changes calls latter. My problem: here all file is being uploaded but only one row inserted in database. Please try to provide me a solution. It will helps me a lot.
so something's up with the updated versions from something. Using vs 2022 and even just the stuff form the first 4 mins didnt work... could you help a little? or update the repo? (I think-)the main error I'm getting is in startup.cs, the " app.UseMvcWithDefaultRoute(); ", with the error message being: " System.InvalidOperationException: "Endpoint Routing does not support 'IApplicationBuilder.UseMvc(...)'. To use 'IApplicationBuilder.UseMvc' set 'MvcOptions.EnableEndpointRouting = false' inside 'ConfigureServices(...)." " and idk how I'm supposed to disable that
Each time I am trying to figure out how to do something you seem to have the perfect video. Thanks for sharing
Cheers :)
Dude, thank you so much, i've learn a lot of useful things from your videos, God bless you.
That is awesome!
Great video!
edited:
Nevermind, little tweaks of your code make my webapps works. Thank you for sharing, this is saving me lots of time!
Thank you for watching:)
Beautiful minds give something complete. Just like this. Blessed the author!
Very Good video, very clear and simple in concept
Thank you
With .NET Core 3.1 instead of IHostingEnvironment it is IWebHostEnvironment.
Thank you for sharing
Great video!!!!
Thanks for sharing!!!
Glad you liked it :)
Hey! Very cool video!
I just have a follow-up question: How do you do Multiple File Upload with Models? For example, if I want to save multiple files in the model, I know you change the IFormFile to a List in the model, but what else changes?
Thanks a lot!
nothing, just select multiple files now )
Thank you so much. it was so helpful
Thank you for watching
Great Great information!
thanks, very well explained
Super useful, thanks
Thanks for watching
Great job !:)
Cheers
Thank you , It's very helpful
Cheers
I wanna use IFormFile or FormFile method in asp.net mvc too. Can we use it? HttpPostedFileBase is easy but I wanna use only one class for upload images and FormFile seems cool.
I think it’s best to use IFormFile
Amazing..
Thanks for Sharing..
Cheers )
Good work
Cheers
this rocks!
No you rock maaaan!
Thank you very much for the nice video, I've couple question what is the maximum size for the upload? if you want to upload 10gb files what would be the best approach?
Thank you! Maximum size of upload for IIS is 28MB, you can change this. Please read the docs docs.microsoft.com/en-us/aspnet/core/mvc/models/file-uploads?view=aspnetcore-3.0#troubleshooting
@@RawCoding Files bigger than 1GB normally require MultiReader Filestreaming instead of IFormFile, otherwise it will just crash with Error 404 due to memory restrictions.
docs.microsoft.com/de-de/aspnet/core/mvc/models/file-uploads?view=aspnetcore-5.0#upload-large-files-with-streaming
Great tutorials anyways!
Thank you for sharing
great job , good video
Cheers))
Hello, could you please show how to display the image in the same page after uploading it.
Thanks for a great video tutorial in uploading files.
Thank you for the suggestion I will make a part 2
Watched the 7 first minutes to get started. Now I has a system that takes the uploaded image. Computes its SHA256 hash and use it as a filename.
Writes the copy of the file into a subfolder.
Works fairly well, but I have 2 issues. Folder should exist prior to writing file. Kinda makes sense from a technical PoV but on the other hand it would be nice if the proper folder is created if needs be. Actually this is Path.Combine that throws the exception because the path which is combined does not exist. So I shall combine the path on its own line in a try/catch and create the folder if needed.
Second issue is I wonder how I should refactor this so that it is clean and reusable amongst my webapp. Creating a service ?
I'll probably watch the rest of the video later.
Thanks for the help.
Sorry for the late response - you should store files in cloud storage really, having a service for that makes the most sense. I have some videos in my Tricking Library series on that, the project source code is freely available as well.
Ахаха чувак ты прям осветил все темы которые мне нужны для дипломной )) респект тебе и уважуха. Кстати один вопрос, я четкого ответа нигде не получил, как лучше хранить музыкальные файлы формата mp3 в базе данных как битовый массив или в файловой системе ?
Спасибо, и удачки на задаче. Мп3 от других файлов сильно не отличаются. Если сохронять как файл то придётся стримить как страничка загрузится. Если как бити то их можна в base64 прям в src кидать или тоже стримить но больше памяти и ресурсов занимать в DB будет. Тоже blob дешевле DB. Я предпочитаю сохронять файли на диск. Если будешь сохронять в DB то делай для них отдельную таблицу id, bytes.
Very well explained. Could you please extend this demo to display progress bars for multiple files async upload.
I'll take a look I'll probably make a new video for net core 3
Thanks You.
Thank you for watching)
Great tutorial! I have a question regarding the path for
axios.post("/Home/SingleFile", formData).
Can I ask you how did the path become "/Home/SingleFile"?
Is it "/`controllerName`/`IActionResult name`"?
Somehow the path is not working, and console throws an error of 400 :(
Yes the way you think about the path is correct. 400 means there is an error, if you don't hit the back end at all and you are using dotnet core 3 you'll have to submit an intiforgery token too.
@@RawCoding Ah ok thanks! I looked up just briefly and i can use The Form Tag Helper with the issue?
@@yoonvak Here's the solution to the issue. stackoverflow.com/a/47633056/5784635
Use @Html.AntiForgeryToken() to generate the anti forgery token and then add it to your request as a __RequestVerificationToken on the request
@@RawCoding Thank you so much! i have a extra question regarding the solution, should I create a new class with the "HttpContextExtensions"? Or can I just add that in the controller where I have the "singleFile" function in it?
@@yoonvak What do you need this extension for?
Thanks for sharing this video. This is a lot clearer video tutorial for uploading a file in ASP.NET core than other video tutorial.
Nice and clean! Thanks again!
By the way, what if i'll be uploading a doc and pdf file? And how to show the uploaded files in the view page?
I hope you could help me out on this. Thanks again!
Thank you for the feedback it's very useful. I'll make a video on how to display uploaded files.
@@RawCoding Yeyy! Looking forward on that.Thanks!
Hey there just to clarify you want to know how to display the contents of these files on the page? Or do you mean list the files that you have uploaded and perhaps download them?
@@RawCoding Hi there! Sorry can't make replies the past days. Yes, I also wanted to download it by users if possible. So the files can be displayed in list and can be downloaded also if possible. Many thanks raw coding 😊
@@RawCoding I need this because currently I'm making a project in our school where they can upload documents in the database and they can also download it when they need. It's more of a document manager where they can sort there documents or search it rather than having it to folders and many subfolders. Sorry if I make confusions but hoping that you could help me. I'm really stuck on this part. Thanks again.
Another great tutorial. Is there a way to view FormData in Chrome Developer tools (view key value pairs)?
Not that I know of unfortunately..
@@RawCoding I agree. I have been looking and have come up short. The best workaround I have found so far is to use get('key') or get('key') from the console. I have also incorporated a check in my JS function call to ensure the value is there. I'm doing all of this because I am running into an issue with .netcore 3 is closing the connection. I am using the JS fetch API. Any idea's on what closes connections or how to debug the issue
prior to reaching the API controller?
nice, tks
Cheers
Do an extented video with security considerations. Thanks!
Hello ppl! One doubt, if I am to implement this functionality in my online shop "create product" admin section, I would have to wrap the "add new product" section into a form then do a post with all the product details from name, description etc to imageFile right? I mean its the best option given the shop implementation isn't it? and then do the appropiate ammenments into the CreateProduct controller action as you are doing in this video. Then in the index page where the products are being displayed, just select the imageFile prop in product.ImageFile for example in order to display that product image. Am I going in the right direction?
Sorry I cannot understand what your problem is
@@RawCoding check in discord please, I'm MostroPlanta ;)
Hi! I am stuck in the same situation right now. Were you able to make it work? :((
Come discord
@@RawCoding Okie thank you!
Sorry, I am having some problems on making this work. The form from the view doesn't reach the parameter in the SingleFile action. It says that it's an unused parameter even though it has the same name
Does it work if you download the source code?
@@RawCoding I tried and it comes with "HTTP Error 500.31 - ANCM Failed to Find Native Dependencies" must be because of the version
Edit: Managed to make it work! Thank youu!!!
Awesome
Hey have you made tutorial on how to upload multiple files over 30MB ?
No, you’ll need to add a setting in Progam.cs if you host on IIS you’ll need a setting in your webconfig, if Linux you’ll need to add a setting to your nginx config
I need to upload to database. Is there a tutorial on that?
there'll be one in Blog series & Tricking Library
Thanks for the video.
Can you please create a similar tutorial for uploading Excel files to a SQL server database using .net core
Cheers and yeah can do!
Notice that in an api web project, the data comes to me in null, I can't upload the image: /
What code are you using to upload the image?
Default model binding is slightly different for API controllers if you added the [ApiControllerAttribute].
I am getting the files, but it is 0 byte long. Is it something to do with async.
Depends on your code
if you have image uploading from subdomain to main domain please kindly share. thanks you
This is a CORS issue
Sounds like a Norwegian :D
Close but no cigar
File is being copied but only last row inserted into database. Please provide solution.
#region File Upload
if (files != null)
{
Attachment oAttachment = new Attachment();
string CaseNo = oCaseInfo.ID;
string newCaseFilePath = Directory.GetCurrentDirectory() + "\\wwwroot" + "\\uploads\\" + CaseNo;
if (!Directory.Exists(newCaseFilePath)) Directory.CreateDirectory(newCaseFilePath); //directory create
foreach (var file in files)
{
if (file.Length > 0)
{
//Getting FileName
var fileName = Path.GetFileName(file.FileName);
//Assigning Unique Filename (Guid)
var myUniqueFileName = Convert.ToString(Guid.NewGuid());
//Getting file Extension
var fileExtension = Path.GetExtension(fileName);
// concatenating FileName + FileExtension
var newFileName = String.Concat(myUniqueFileName, fileExtension);
oAttachment.CaseID = oCaseInfo.ID;
oAttachment.AttachmentName = fileName;
oAttachment.ModifiedAttachmentName = myUniqueFileName + fileExtension;
oAttachment.SetupDate = DateTime.Now;
oAttachment.AttachmentPath = newCaseFilePath;
// Combines two strings into a path.
var filepath = newCaseFilePath + "\\" + newFileName;
//var filepath = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "Images")).Root + $@"\{newFileName}";
using (FileStream fs = System.IO.File.Create(filepath))
{
file.CopyTo(fs);
fs.Flush();
}
_db.Attachment.Add(oAttachment);
}
}
}
#endregion
Seems like you only have 1 attachment reference and no save changes call
@@RawCoding Brother,
1. multiple attachment exists (Hints: foreach (var file in files) )
2. This is a part of a code. save changes calls latter.
My problem: here all file is being uploaded but only one row inserted in database. Please try to provide me a solution. It will helps me a lot.
You have a single attachment reference, 1 object, Uno variable . You never create more than 1 attachment
@@RawCoding Please give me the correction code.
I’m on phone. Put the attachment inside your loop. Create a new object for each file
By This way, Can You Upload a PDF file ?
Any file, in the end they are all just bytes
@@RawCoding Thank You Sir
so something's up with the updated versions from something. Using vs 2022 and even just the stuff form the first 4 mins didnt work... could you help a little? or update the repo?
(I think-)the main error I'm getting is in startup.cs, the " app.UseMvcWithDefaultRoute(); ", with the error message being: " System.InvalidOperationException: "Endpoint Routing does not support 'IApplicationBuilder.UseMvc(...)'. To use 'IApplicationBuilder.UseMvc' set 'MvcOptions.EnableEndpointRouting = false' inside 'ConfigureServices(...)." "
and idk how I'm supposed to disable that