ASP.NET Core File Upload Tutorial

Поділитися
Вставка
  • Опубліковано 31 жов 2024

КОМЕНТАРІ • 110

  • @uzeirdalip9499
    @uzeirdalip9499 4 роки тому +3

    Each time I am trying to figure out how to do something you seem to have the perfect video. Thanks for sharing

  • @hutzpa3619
    @hutzpa3619 4 роки тому +5

    Dude, thank you so much, i've learn a lot of useful things from your videos, God bless you.

  • @Patrick-il3uy
    @Patrick-il3uy 4 роки тому +15

    With .NET Core 3.1 instead of IHostingEnvironment it is IWebHostEnvironment.

    • @RawCoding
      @RawCoding  4 роки тому +1

      Thank you for sharing

  • @alifrahmanputranda1463
    @alifrahmanputranda1463 4 роки тому +1

    Great video!
    edited:
    Nevermind, little tweaks of your code make my webapps works. Thank you for sharing, this is saving me lots of time!

    • @RawCoding
      @RawCoding  4 роки тому +1

      Thank you for watching:)

  • @mebtuabebe8428
    @mebtuabebe8428 11 місяців тому

    Beautiful minds give something complete. Just like this. Blessed the author!

  • @victorcaceres3592
    @victorcaceres3592 4 роки тому +1

    Very Good video, very clear and simple in concept

  • @evaapperson1760
    @evaapperson1760 2 роки тому +1

    Great job !:)

  • @niglavinas
    @niglavinas Рік тому

    Great Great information!

  • @kristiyanivanov7414
    @kristiyanivanov7414 3 роки тому +1

    Super useful, thanks

  • @argeelearner3978
    @argeelearner3978 4 роки тому +1

    Great video!!!!
    Thanks for sharing!!!

  • @Lovelymusic_site
    @Lovelymusic_site 2 роки тому +1

    Thank you so much. it was so helpful

    • @RawCoding
      @RawCoding  2 роки тому

      Thank you for watching

  • @ucthienphan1729
    @ucthienphan1729 2 роки тому

    thanks, very well explained

  • @danyalkhan74
    @danyalkhan74 3 роки тому +2

    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!

    • @RawCoding
      @RawCoding  3 роки тому +1

      nothing, just select multiple files now )

  • @shuozhao3286
    @shuozhao3286 4 роки тому +1

    Thank you , It's very helpful

  • @raphaelnanet
    @raphaelnanet 3 роки тому +1

    Good work

  • @saifshaikh3256
    @saifshaikh3256 4 роки тому +1

    Amazing..
    Thanks for Sharing..

  • @АристархЗловредович

    Ахаха чувак ты прям осветил все темы которые мне нужны для дипломной )) респект тебе и уважуха. Кстати один вопрос, я четкого ответа нигде не получил, как лучше хранить музыкальные файлы формата mp3 в базе данных как битовый массив или в файловой системе ?

    • @RawCoding
      @RawCoding  4 роки тому +2

      Спасибо, и удачки на задаче. Мп3 от других файлов сильно не отличаются. Если сохронять как файл то придётся стримить как страничка загрузится. Если как бити то их можна в base64 прям в src кидать или тоже стримить но больше памяти и ресурсов занимать в DB будет. Тоже blob дешевле DB. Я предпочитаю сохронять файли на диск. Если будешь сохронять в DB то делай для них отдельную таблицу id, bytes.

  • @cestarop
    @cestarop 3 роки тому +1

    this rocks!

  • @objetdeluxure
    @objetdeluxure 5 років тому +1

    great job , good video

  • @EminoMeneko
    @EminoMeneko 3 роки тому +1

    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.

    • @RawCoding
      @RawCoding  3 роки тому

      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.

  • @onemorestory1
    @onemorestory1 4 роки тому +2

    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.

    • @RawCoding
      @RawCoding  4 роки тому +1

      I think it’s best to use IFormFile

  • @CrivatFlorin
    @CrivatFlorin 2 роки тому

    Do an extented video with security considerations. Thanks!

  • @johnlesterlumbao9546
    @johnlesterlumbao9546 5 років тому +1

    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!

    • @RawCoding
      @RawCoding  5 років тому +1

      Thank you for the feedback it's very useful. I'll make a video on how to display uploaded files.

    • @johnlesterlumbao9546
      @johnlesterlumbao9546 5 років тому +1

      @@RawCoding Yeyy! Looking forward on that.Thanks!

    • @RawCoding
      @RawCoding  5 років тому +1

      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?

    • @johnlesterlumbao9546
      @johnlesterlumbao9546 5 років тому +1

      @@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 😊

    • @johnlesterlumbao9546
      @johnlesterlumbao9546 5 років тому +1

      @@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.

  • @rayt6867
    @rayt6867 5 років тому +2

    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.

    • @RawCoding
      @RawCoding  5 років тому +1

      Thank you for the suggestion I will make a part 2

  • @juanalfredogutierrez8663
    @juanalfredogutierrez8663 4 роки тому +1

    Thanks You.

    • @RawCoding
      @RawCoding  4 роки тому

      Thank you for watching)

  • @yoonvak
    @yoonvak 4 роки тому +1

    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 :(

    • @RawCoding
      @RawCoding  4 роки тому

      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
      @yoonvak 4 роки тому +1

      @@RawCoding Ah ok thanks! I looked up just briefly and i can use The Form Tag Helper with the issue?

    • @RawCoding
      @RawCoding  4 роки тому +1

      @@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

    • @yoonvak
      @yoonvak 4 роки тому +1

      @@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?

    • @RawCoding
      @RawCoding  4 роки тому

      @@yoonvak What do you need this extension for?

  • @vanquangnguyen8335
    @vanquangnguyen8335 3 роки тому +1

    nice, tks

  • @grapepanta3712
    @grapepanta3712 3 роки тому +1

    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
      @RawCoding  3 роки тому

      Does it work if you download the source code?

    • @grapepanta3712
      @grapepanta3712 3 роки тому +1

      @@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!!!

    • @RawCoding
      @RawCoding  3 роки тому

      Awesome

  • @fkamss
    @fkamss 5 років тому +1

    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?

    • @RawCoding
      @RawCoding  5 років тому +1

      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

    • @MperAule
      @MperAule 3 роки тому +1

      @@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!

    • @RawCoding
      @RawCoding  3 роки тому

      Thank you for sharing

  • @brijenders
    @brijenders 4 роки тому +1

    Very well explained. Could you please extend this demo to display progress bars for multiple files async upload.

    • @RawCoding
      @RawCoding  4 роки тому

      I'll take a look I'll probably make a new video for net core 3

  • @abelpaz5960
    @abelpaz5960 4 роки тому +1

    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?

    • @RawCoding
      @RawCoding  4 роки тому +1

      Sorry I cannot understand what your problem is

    • @abelpaz5960
      @abelpaz5960 4 роки тому

      @@RawCoding check in discord please, I'm MostroPlanta ;)

    • @badadumb9558
      @badadumb9558 3 роки тому +1

      Hi! I am stuck in the same situation right now. Were you able to make it work? :((

    • @RawCoding
      @RawCoding  3 роки тому

      Come discord

    • @badadumb9558
      @badadumb9558 3 роки тому

      @@RawCoding Okie thank you!

  • @kevin179887
    @kevin179887 4 роки тому +1

    Another great tutorial. Is there a way to view FormData in Chrome Developer tools (view key value pairs)?

    • @RawCoding
      @RawCoding  4 роки тому

      Not that I know of unfortunately..

    • @kevin179887
      @kevin179887 4 роки тому

      @@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?

  • @madhumithaselvam3264
    @madhumithaselvam3264 3 роки тому +1

    I need to upload to database. Is there a tutorial on that?

    • @RawCoding
      @RawCoding  3 роки тому

      there'll be one in Blog series & Tricking Library

  • @ownagepk1ng
    @ownagepk1ng 3 роки тому +1

    Hey have you made tutorial on how to upload multiple files over 30MB ?

    • @RawCoding
      @RawCoding  3 роки тому

      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

  • @peterrasmussen2384
    @peterrasmussen2384 3 роки тому

    I am getting the files, but it is 0 byte long. Is it something to do with async.

  • @sharifahmed1925
    @sharifahmed1925 5 років тому +1

    Thanks for the video.
    Can you please create a similar tutorial for uploading Excel files to a SQL server database using .net core

    • @RawCoding
      @RawCoding  5 років тому

      Cheers and yeah can do!

  • @angelortiz6627
    @angelortiz6627 4 роки тому +1

    Notice that in an api web project, the data comes to me in null, I can't upload the image: /

    • @RawCoding
      @RawCoding  4 роки тому

      What code are you using to upload the image?

    • @RDWize
      @RDWize 3 роки тому

      Default model binding is slightly different for API controllers if you added the [ApiControllerAttribute].

  • @bunthakh
    @bunthakh 3 роки тому

    if you have image uploading from subdomain to main domain please kindly share. thanks you

  • @mazidulislamzahid6057
    @mazidulislamzahid6057 3 роки тому +1

    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

    • @RawCoding
      @RawCoding  3 роки тому

      Seems like you only have 1 attachment reference and no save changes call

    • @mazidulislamzahid6057
      @mazidulislamzahid6057 3 роки тому +1

      @@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.

    • @RawCoding
      @RawCoding  3 роки тому

      You have a single attachment reference, 1 object, Uno variable . You never create more than 1 attachment

    • @mazidulislamzahid6057
      @mazidulislamzahid6057 3 роки тому +1

      @@RawCoding Please give me the correction code.

    • @RawCoding
      @RawCoding  3 роки тому

      I’m on phone. Put the attachment inside your loop. Create a new object for each file

  • @H3000-v7i
    @H3000-v7i 4 роки тому +1

    Sounds like a Norwegian :D

  • @khalidabuhijleh3475
    @khalidabuhijleh3475 4 роки тому

    By This way, Can You Upload a PDF file ?

  • @mrniffels
    @mrniffels 2 роки тому

    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