Upload Document in the Asp.Net Core Application

How to Upload Files / Documents in the Asp.Net Core 3.1 Application.

December 11, 2020

In this article we will cover how to Upload Document in the Asp.Net Core 3.1 Application.

Resume.cs

Create Resume.cs class inside "Models" folder and replace the code with given below.

With Data Annotations the class also has custom validation, which validates the document size and document extension.

using Microsoft.AspNetCore.Http;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.IO;
 
public class Resume : IValidatableObject
{
    [Required]
    [DataType(DataType.Upload)]
    public IFormFile Resume_Upload { getset; }
    
    [Required]
    public string Resume_Bio { getset; }
    
    [Required]
    public string Resume_Title { getset; }
    public string Resume_Ext { getset; }
    public string Resume_Name { getset; }
    public IEnumerable<ValidationResultValidate(ValidationContext validationContext)
    {
        var resume = ((Resume)validationContext.ObjectInstance).Resume_Upload;
        var extension = Path.GetExtension(resume.FileName);
        var size = resume.Length;
 
        if (!extension.ToLower().Equals(".doc") && !extension.ToLower().Equals(".docx") && !extension.ToLower().Equals(".pdf"))
            yield return new ValidationResult("File extension is not valid.");
 
        if (size > (5 * 1024 * 1024))
            yield return new ValidationResult("File size is bigger than 5MB.");
    }
}

ResumeController.cs

Create ResumeController.cs class inside "Controllers" folder and replace the code with given below.

using System;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using System.Text;
using System.Linq;
using System.IO;
 
public class ResumeController : Controller
{
    public IActionResult Index()
    {
        return View(new Resume());
    }
 
    [HttpPost]
    [RequestFormLimits(ValueLengthLimit = int.MaxValue, MultipartBodyLengthLimit = int.MaxValue)]
    public async Task<IActionResultIndex(Resume model)
    {
        if (ModelState.IsValid)
        {
            foreach (var file in Request.Form.Files)
            {
                if (file.Length == 0)
                    ModelState.AddModelError("ModelError""please provide valid file");
 
                var fileName = (model.Resume_Title + "_" + DateTime.Now.ToString("dd_MMM_yyyy_hhmmss") + Path.GetExtension(file.FileName)).Replace(" ""_");
 
                // 1) Upload file to any cloud stoarege or database 
                using (var fileStream = file.OpenReadStream())
                using (var ms = new MemoryStream())
                {
                    await fileStream.CopyToAsync(ms);
                    //bool status = await _Service.UploadFileAsync(ms, fileName); // Call Upload Api
                }
 
                // 2) Save file to local path in Resumes folder
                var path = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot""Resumes"fileName);
                using (var stream = new FileStream(pathFileMode.Create))
                {
                    await file.CopyToAsync(stream);
                }
 
                // 3) Insert data in the database 
                Resume obj = new Resume();
                obj.Resume_Bio = model.Resume_Bio;
                obj.Resume_Title = model.Resume_Title;
                obj.Resume_Name = fileName;
                obj.Resume_Ext = Path.GetExtension(file.FileName);
 
                var content = new StringContent(JsonConvert.SerializeObject(obj), Encoding.UTF8, "application/json");
 
                //Call API or Write Database code directly
                //var resput = client.PostAsync($"Resume", content).Result; 
 
                return Redirect("/resume");
            }
        }
        else
        {
            ModelState.AddModelError("ModelError", ModelState.FirstOrDefault().Value.Errors.FirstOrDefault().ErrorMessage);
        }
        return View(model);
    }
}

Index.cshtml

Create "Resume" Folder inside "Views" and the Index.cshtml inside "Resume" and replace the code with given below.

@model Resume
 
<form method="post" enctype="multipart/form-data">
    <h3>Upload Resume</h3>
 
    <div class="form-group">
        <div class="upload-btn-box">
            <input type="file" asp-for="Resume_Upload" />
            <p>Max file size is 5MB, Allowed files are .doc, .docx, .pdf</p>
        </div>
        <span class="error">
            @Model.Resume_Name
        </span>
        <span asp-validation-for="Resume_Upload" class="text-danger"></span>
        <span class="error">@Html.ValidationMessage("ModelError")</span>
    </div>
 
    <div class="form-group">
        <label>Resume Title</label>
        <div class="form-group">
            <input asp-for="Resume_Title" />
            <span asp-validation-for="Resume_Title" class="error"></span>
        </div>
    </div>
    <div class="input-box">
        <label>Bio</label>
        <div class="form-group">
            <textarea class="form-control" asp-for="Resume_Bio" placeholder="Bio Info"></textarea>
            <span asp-validation-for="Resume_Bio" class="error"></span>
        </div>
    </div>
    <button type="submit">Upload</button>
</form>

Post Comments(0)

Leave a reply

Will not be displayed in comment box .

Loading...