Exploring the Code behind.

To start with, need first need to create a new project by opening Visual Studio and select .NET Framework CORE 2.1. Next select ASP.NET Web Application, move on to Empty project and select Web Api. This will create a blank project for us.

Now, create a new controller named UploadController and add the following code in it.

    [EnableCors("CorsPolicy")]
    [Produces("application/json")]
    [Route("api/[controller]")]
    public class UploadController : Controller
    {
        private IHostingEnvironment _hostingEnvironment;
 
        public UploadController(IHostingEnvironment hostingEnvironment)
        {
            _hostingEnvironment = hostingEnvironment;
        }
 
        [HttpPost, DisableRequestSizeLimit]
        public ActionResult UploadFile()
        {
            try
            {
                var file = Request.Form.Files[0];
                string folderName = "Upload";
                string webRootPath = _hostingEnvironment.WebRootPath;
                string newPath = Path.Combine(webRootPath, folderName);
                if (!Directory.Exists(newPath))
                {
                    Directory.CreateDirectory(newPath);
                }
                if (file.Length > 0)
                {
                    string fileName = ContentDispositionHeaderValue
.Parse(file.ContentDisposition).FileName.Trim(');                     string fullPath = Path.Combine(newPath, fileName);                     using (var stream = new FileStream(fullPath, 
FileMode.Create))                     {                         file.CopyTo(stream);                     }                 }                                  return Json("Upload Successful.");             }             catch (System.Exception ex)             {                 return Json("Upload Failed: " + ex.Message);             }         }     }

Code explaination:-

[EnableCors("CorsPolicy")]
[Produces("application/json")]
[Route("api/[controller]")]
  1. Annotations which we added at the controller level defines that we want CORS to be enabled, result to be returned as json and routing to start with api/controller name.

  2. Declaring IHostingEnvironment interface and inject IHostingEnvironment inside the constructor of controller.

  3. Create action method named UploadFile. Inside the method we will see if there's any file within forms request, create a directory where we will upload file.

  4. Now read file from current request as file stream and file.CopyTo will upload file in the respective folder.

  5. Inside Startup file add the following code to add CORS policy
// This method gets called by the runtime. Use this method to 
add services to the container. public void ConfigureServices(IServiceCollection services) {     // services.AddMvc();     //services.AddCors();          services.AddCors(options =>     {                   options.AddPolicy("CorsPolicy",            builder => builder.AllowAnyOrigin()           .AllowAnyMethod()           .AllowAnyHeader()           .AllowCredentials());     });

Now we are done with the code, lets check with postman how it works. In the postman we do a method post, select post as form-data, choose filetype as file. select desired file to upload, you will see the file uploaded success.





blog comments powered by Disqus