771 views
asked in Asp.Net Core MVC by
Asp.Net Core MVC Tutorial - Upload a pdf/file in network share drive in Asp.Net Core MVC

1 Answer

answered by

Uploading a PDF to a network share drive in a .NET Core MVC application involves creating a view with a file upload form, handling the file upload in the controller, and saving the file to the network share directory. Here are the steps:

  1. Create the View:

    • Add a new view with a file upload form.
<!-- Views/Home/Upload.cshtml -->
@*
    For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
*@
@{
    @model UploadViewModel
    <form asp-action="Upload" asp-controller="Home" method="post" enctype="multipart/form-data">
        <div class="form-group">
            <label for="File">Upload PDF</label>
            <input type="file" class="form-control" id="File" name="File" />
        </div>
        <button type="submit" class="btn btn-primary">Upload</button>
    </form>

    @if (ViewBag.Message != null)
    {
        <div class="alert alert-info">
            @ViewBag.Message
        </div>
    }
}


2. Create the View Model:

  • Add a view model to handle the uploaded file.
// Models/UploadViewModel.cs
using Microsoft.AspNetCore.Http;

namespace fileUploadCoreMvc.Models
{
    public class UploadViewModel
    {
        public IFormFile File { get; set; }
    }
}

3. Create the Controller:

  • In the controller, handle the file upload and save it to the network share directory.
// Controllers/HomeController.cs
using fileUploadCoreMvc.Models;
using Microsoft.AspNetCore.Mvc;
using System.Diagnostics;
using System;
using System.IO;
using System.Threading.Tasks;

namespace fileUploadCoreMvc.Controllers
{
    public class HomeController : Controller
    {
        private readonly ILogger<HomeController> _logger;

        public HomeController(ILogger<HomeController> logger)
        {
            _logger = logger;
        }

        public IActionResult Index()
        {
            return View();
        }

        public IActionResult Privacy()
        {
            return View();
        }

        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }

        [HttpGet]
        public IActionResult Upload()
        {
            return View();
        }

        [HttpPost]
        public async Task<IActionResult> Upload(UploadViewModel model)
        {
            if (model.File != null && model.File.Length > 0)
            {
                try
                {
                    string fileName = Path.GetFileName(model.File.FileName);
                    string networkPath = @"\\172.16.20.62\AppData_MMMSY\" + fileName;

                    using (var stream = new FileStream(networkPath, FileMode.Create))
                    {
                        await model.File.CopyToAsync(stream);
                    }

                    ViewBag.Message = "File uploaded successfully!";
                }
                catch (Exception ex)
                {
                    ViewBag.Message = "Error: " + ex.Message;
                }
            }
            else
            {
                ViewBag.Message = "Please select a file to upload.";
            }

            return View();
        }
    }
}
  • 4. Ensure Permissions:

    • Ensure that the application pool identity or the user account running the application has write permissions to the network share directory.
    • Set permissions in the network share properties by adding the appropriate user and granting the necessary permissions.
  • By following these steps, you can create a .NET Core MVC application that allows users to upload a PDF file to a network share directory. Make sure to handle exceptions and edge cases as needed for your specific use case.




Most popular tags

laravel postgresql laravel-10 replication ha postgresql mongodb laravel-11 mongodb database mongodb tutorial ubuntu 24.04 lts streaming-replication mysql database laravel postgresql backup laravel login register logout database mysql php laravel 11 - login with otp valid for 10 minutes. user and admin registration user and admin login multiauth technlogy asp.net asp.net c# mysql master slave replication centos linux laravel sql server schedule backup autobackup postgresql django python haproxy load balancer install self sign ssl laravel 11 gaurds zabbix 7 how to install graylog on ubuntu 24.04 lts | step-by-step asp.net core mvc .net mvc network upload c# ssl integration sql server on ubuntu 22.04 lts mssql server ms sql server sql server user access in postgres mysql password change cent os linux configure replica laravel 11 socialite login with google account google login kubernetes (k8s) install nginx load balancer install install and configure .net 8.0 in ubuntu 24.04 lts php in iis php with iis php tutorial chirags php tutorials chirags php tutorial chirags tutorial laravel 11 guards mongodb sharding metabase business analytics metabase postgresql 16 to postgresql 17 postgresql migration letsencrypt mongodb crud rocky linux laravel custom captcha laravel 11 captcha laravel captcha mongo dll php.ini debian 12 nginx apache nextcloud gitea in ubuntu git gitea npm error node js mysql ndb cluster mysql cluster ssl oracle login register logout in python debian windows shell batch file bat file time stamp date time shopping cart in laravel centos rhel swap memeory rhel 5.5
...