find and solve || findandsolve.com
Please wait.....

ASP.NET Core File Upload with Form Data

ASP.NET Core File Upload with Form Data

In ASP.NET Core, you can use the IFormFile interface to handle file uploads with form data. Here's an example of how you can implement file upload in an ASP.NET Core controller:

Create ViewModel for Upload image file names given below

  public class FileViewModel
    {
         public IFormFile File{ get; set; }
         public string FilePath{get;set;}
         public string FileName{get;set;}
    }
//About IFormFile more details click here

  Create action method in file controller  as given below


using System;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.FileProviders;
namespace FIleUploadExample.Controllers
{
 public class FileController : Controller 
 {
    private readonly IHostingEnvironment _hostingEnvironment;

  //call IHostingEnvironment in constructor as given below.This is use for server default hosting path
 public FileController(IHostingEnvironment hostingEnvironment)
   {
    
    _hostingEnvironment=hostingEnvironment;
   }
   public IActionResult FileUpload()
        {
            return View();
         //create new view page
        }
  [HttpPost]
  public IActionResult FileUpload(FileViewModel model){
    {
          //check file null or not
           if (model.File== null)
            {
                ModelState.AddModelError("", "File is not selected");
                return View();
            }
             string rootFolder = _hostingEnvironment.WebRootPath;
             var guId= Guid.NewGuid().ToString(); //Guid create new string value which is always unique
            //Combination of file name and root folder where  file are stored.
             string fileName = @"StoreFolder/" + guId + model.File.FileName;
           //@"StoreFolder= folder name where i have store file or image 
           
          string  filePath = Path.Combine(rootFolder, fileName);
           //filePath is a combination of  hosting  path and  file store path
            using (var fileStream = new FileStream(filePath, FileMode.Create))
            {
                 model.File.CopyToAsync(fileStream);
            }
            //we have saved file in StoreFolder .Now we are going to save file path in database as given below
              
           model.FilePath=fileName ;
         //After that map ViewModel to Entity and save the image file path in your database
         //Crete connection object 
           <your connection> _context = new <your connection>();
         //Create yout tabe entity object
        <your-table-entity> tabeEntity = new <your-table-entity>();
        //map viewmodel to entity model as given below
           tabeEntity.FilePaht =fileName; 
          tabeEntity.FileName=model.File.FileName; 
           EntityEntry dbEntityEntry = _context.Entry(entity);
                _context.Set<tabeEntity>().Add(entity);
                _context.SaveChanges();
    }
}

  Create new view FileUpload in your project and past the code as given below

                    //view model path
                    @model FileViewModel
                  @{
                        ViewData["Title"] = "File Update Example";
                        Layout = "~/Views/Shared/_Layout.cshtml";
                     }
             <form asp-action="FileUpload" class="text-left form-validate" enctype="multipart/form-data">
                                                                                          
                    <input asp-for="File" type="file" id="chooseFile">
                   <button type="submit" class="btn btn-primary">Upload File</button>
                              
              </form>

//Full File Update View Page


                 @model FileViewModel
                  @{
                        ViewData["Title"] = "File Update Example";
                        Layout = "~/Views/Shared/_Layout.cshtml";
                     }
<style>
    /*Custom File Upload Css By: Find and  solve*/
    .file-upload {
        display: block;
        text-align: center;
        font-family: Helvetica, Arial, sans-serif;
        font-size: 12px;
    }
        .file-upload .file-select {
            display: block;
            border: 1px solid #ddd;
            color: #34495e;
            cursor: pointer;
            height: calc(2.325rem + 2px);
            line-height: 40px;
            text-align: left;
            background: #FFFFFF;
            overflow: hidden;
            position: relative;
        }
            .file-upload .file-select .file-select-button {
                background: #dce4ec;
                padding: 0 10px;
                display: inline-block;
                height: calc(2.325rem + 2px);
                line-height: 40px;
            }
            .file-upload .file-select .file-select-name {
                line-height: 40px;
                display: inline-block;
                padding: 0 10px;
            }
            .file-upload .file-select:hover {
                border-color: #34495e;
                transition: all .2s ease-in-out;
                -moz-transition: all .2s ease-in-out;
                -webkit-transition: all .2s ease-in-out;
                -o-transition: all .2s ease-in-out;
            }
                .file-upload .file-select:hover .file-select-button {
                    background: #34495e;
                    color: #FFFFFF;
                    transition: all .2s ease-in-out;
                    -moz-transition: all .2s ease-in-out;
                    -webkit-transition: all .2s ease-in-out;
                    -o-transition: all .2s ease-in-out;
                }
        .file-upload.active .file-select {
            border-color: #33b35a;
            transition: all .2s ease-in-out;
            -moz-transition: all .2s ease-in-out;
            -webkit-transition: all .2s ease-in-out;
            -o-transition: all .2s ease-in-out;
        }
            .file-upload.active .file-select .file-select-button {
                background: #33b35a;
                color: #FFFFFF;
                transition: all .2s ease-in-out;
                -moz-transition: all .2s ease-in-out;
                -webkit-transition: all .2s ease-in-out;
                -o-transition: all .2s ease-in-out;
            }
        .file-upload .file-select input[type=file] {
            z-index: 100;
            cursor: pointer;
            position: absolute;
            height: 100%;
            width: 100%;
            top: 0;
            left: 0;
            opacity: 0;
            filter: alpha(opacity=0);
        }
        .file-upload .file-select.file-select-disabled {
            opacity: 0.65;
        }
            .file-upload .file-select.file-select-disabled:hover {
                cursor: default;
                display: block;
                border: 1px solid #ddd;
                color: #34495e;
                cursor: pointer;
                height: 40px;
                line-height: 40px;
                margin-top: 5px;
                text-align: left;
                background: #FFFFFF;
                overflow: hidden;
                position: relative;
            }
                .file-upload .file-select.file-select-disabled:hover .file-select-button {
                    background: #dce4ec;
                    color: #666666;
                    padding: 0 10px;
                    display: inline-block;
                    height: 40px;
                    line-height: 40px;
                }
                .file-upload .file-select.file-select-disabled:hover .file-select-name {
                    line-height: 40px;
                    display: inline-block;
                    padding: 0 10px;
                }
 .breadcrumb-holder .breadcrumb {
    padding: 15px 0;
    font-size: 0.85em;
    font-weight: 500;
    color: black;
    margin-bottom: 0;
}
}
</style>

<!-- Breadcrumb-->
<div class="breadcrumb-holder">
    <div class="container-fluid">
        <ul class="breadcrumb">
            Header Link 
        </ul>
      
    </div>
</div>
<form asp-action="ImportiFrameUser" class="text-left form-validate" enctype="multipart/form-data">
    <section class="forms">
        <div class="container-fluid">
            <header>
                <h1 class="h3 display"></h1>
                Heading section 
                <br />
                <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            </header>
            <div class="row">
                <div class="col-lg-12">
                    <div class="card">
                        <div class="card-body">
                            <div class="form-group row">
                                <div class="col-sm-10">
                                    <div class="file-upload">
                                        <div class="file-select">
                                            
                                          
                                            <div class="file-select-button" id="fileName">Upload File</div>
                                            <div class="file-select-name" id="noFile">No file chosen...</div>
                                            <input asp-for="File" type="file" id="chooseFile">
                                        </div>
                                    </div>
                                </div>
                                <div class="col-sm-2">
                                    <button type="submit" class="btn btn-primary">Upload File</button>
                                </div>
                            </div>
                           
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </section>
</form>
Note that you need to set the enctype attribute of the form element to "multipart/form-data" so that the browser sends the file and the other form data in a multipart message. Also, you should also validate the uploaded file for its size and format before saving it to the server.                                                 

Related information

Sundar  Neupane

Sundar Neupane

I like working on projects with a team that cares about creating beautiful and usable interfaces.

If findandsolve.com felt valuable to you, feel free to share it.

Comments



Report Response