Upload Large Files In Web API With A Simple Method

There are many good tutorials available on the web about uploading large files in Web API. C# Corner also has a very nice article Upload Large Files To MVC / WebAPI Using Partitioning by one of the great authors Allen O'Neill.

In this article, we will see a very simple method to upload large files in the Web API project using MultipartFormDataStreamProvider.

We can create a Web API project in Visual Studio 2017/2015. I am using Visual Studio 2017 community edition.

Web API project in Visual Studio 

After some time
, our project will be created with default templates.

We must change the value of “maxAllowedContentLength” in requestLimits” in web configuration file to 1GB. If your upload file size is more than 1GB, please change the settings accordingly.

maxAllowedContentLength 

We gave the value in Bytes.

We must change the settings under system.webServer node in the web.config file.

We can add more settings in the web.config file for the location of our files to be stored.

web.config file 

Our configuration part is over. Now, let’s create a new API controller.

new API controller 

We can add the below code to this controller.
  1. public class FileuploadController : ApiController  
  2.     {  
  3.         public async Task<bool> Upload()  
  4.         {  
  5.             try  
  6.             {  
  7.                 var fileuploadPath = ConfigurationManager.AppSettings["FileUploadLocation"];  
  8.   
  9.                 var provider = new MultipartFormDataStreamProvider(fileuploadPath);  
  10.                 var content = new StreamContent(HttpContext.Current.Request.GetBufferlessInputStream(true));  
  11.                 foreach (var header in Request.Content.Headers)  
  12.                 {  
  13.                     content.Headers.TryAddWithoutValidation(header.Key, header.Value);  
  14.                 }  
  15.   
  16.                 await content.ReadAsMultipartAsync(provider);  
  17.   
  18.                 return true;  
  19.             }  
  20.             catch (Exception)  
  21.             {  
  22.                 return false;  
  23.             }  
  24.   
  25.         }  
  26.     }  

We created a provider variable with “MultipartFormDataStreamProvider” and content variable with “StreamContent”. Then we added the Request headers to a content variable using a FOR Loop.

Finally, we read the multi-part data from the content variable asynchronously. It will automatically create a file in the given folder. (We gave the output path as a web configuration parameter)

We can use the postman tool to test our Web
API. Please run our Web API now. After our Web API loaded, we can come to postman tool and using POST method we can send a request to Web API. We must choose “form-data” in the body part and choose “File” as type.

POST method

We can click the “Send” button now. After some time, we will get a result.

Result 

We got a “true” result. That means, our file upload successfully completed. Now we can check the file location (which we mentioned in the the
web.config file).

location  

Please note though our file uploaded successfully, we got a different random file name in the uupload location without any extension.

We can add one 
simple step to rename the file name with the original file name.
  1. //Code for renaming the random file to Original file name  
  2.                string uploadingFileName = provider.FileData.Select(x => x.LocalFileName).FirstOrDefault();  
  3.                string originalFileName = String.Concat(fileuploadPath, "\\" + (provider.Contents[0].Headers.ContentDisposition.FileName).Trim(new Char[] { '"' }));  
  4.   
  5.                if (File.Exists(originalFileName))  
  6.                {  
  7.                    File.Delete(originalFileName);  
  8.                }  
  9.   
  10.                File.Move(uploadingFileName, originalFileName);  
  11.                //Code renaming ends...  

Please execute the postman with the same file again and see the difference.

Upload Large Files In Web API

Please note, our file successfully uploaded with the original file name. We tested the application with a very small 
file (less than 2MB).

Now we can test with a large-sized 
file (File size is 708 MB).

Upload Large Files In Web API
After some time, our large file will be uploaded successfully. You can now check the file upload folder and see the new file there.

Upload Large Files In Web API 
In this article, we saw very simple steps to upload large files in Web APIs. You can use the same code for any large file. As this is a Web API, we can use this with any client-side application (Windows or Web).


Similar Articles