Skip to main content

How to upload files by using ASP.NET Core

Many web applications require users to upload files. Whether it’s a photo, document or any other type of file, your application should be able to read it from the client computer and store it in the server.

I have recently worked on a case where the developer were trying to use the functions below to get the full path of the file:

string filePath = Path.Combine(Request.Form["file"].ToString());
string filePath = System.IO.Path.GetFullPath(Request.Form["file"].ToString());

These functions won’t return the full path if “Include local directory path when uploading files to a server” setting is disabled in Internet Explorer.

When a file is selected by using the input type=file object, the value of the value property depends on the value of the”Include local directory path when uploading files to a server” security setting for the security zone used to display the Web page containing the input object. The fully qualified filename of the selected file is returned only when this setting is enabled. When the setting is disabled, Internet Explorer 8 replaces the local drive and directory path with the string C:\fakepath\ in order to prevent inappropriate information disclosure.

Source
Upload files

Even if you enable this setting, you may still not get the full path (or get a fake path) if the <input> control has only file name in it.

This method uses the current directory and current volume information to fully qualifypath. If you specify a file name only in path,GetFullPath returns the fully qualified path of the current directory.

Source

Instead of trying to get the full path from <input> control and find a way to upload it to the server, I would recommend using List<IFormFile>.

Upload files by using fileUpload control

Use code below to upload a file from a local or network folder. This code will read the file content and save it to the temp folder of the server (C:\Windows\TEMP). The file name won’t be the same in the TEMP folder (filePath variable shows the full path with the file name).

cshtml file:

<h1>Upload Files</h1>
<divclass="row">
   <section>
       <formmethod="post"enctype="multipart/form-data"
             asp-controller="UploadFiles"asp-action="Index">
           <divclass="form-group">
               <divclass="col-md-10">
                   <p>Upload one or more files using this form:</p>
                    <inputtype="file"name="files"multiple/>
               </div>
           </div>
           <divclass="form-group">
               <divclass="col-md-10">
                   <inputtype="submit"value="Upload"/>
               </div>
           </div>
       </form>
   </section>
</div>

cs file:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
 
namespace fileUpload.Pages
{
   publicclassIndexModel : PageModel
    {
       publicvoid OnGet()
        {
 
        }
 
 
        [HttpPost]
       public IActionResult OnPost(List<IFormFile> files)
        {
 
           long size = files.Sum(f => f.Length);
 
           // full path to file in temp location
           var filePath = Path.GetTempFileName();
 
           foreach (var formFilein files)
            {
               if (formFile.Length > 0)
                {
                   using (var stream = new FileStream(filePath, FileMode.Create))
                    {
                        formFile.CopyTo(stream);
                    }
                }
            }
 
            System.IO.File.WriteAllText("C:\\test\\variable.txt", filePath);
           
            return Page();
        }
    }
}

If you are uploading a big file, you may reach the IIS limit and receive HTTP 413 error. Here is the solution: HTTP status 413 (Request Entity Too Large)

Leave a Reply

Your email address will not be published. Required fields are marked *