Download byte array as a file in ASP .NET MVC and Javascript

Author - Harleen Kaur
6.09.2018
|
0 Comments
||

How to download byte array as a file in ASP .NET MVC and Javascript?

Here is a simple approach to invoke file download operation in the browser for bytes array available on the server:

I am receiving the file in the format of bytes array from some third party service and I needed to save this file on the client machine without first saving it on server i.e in my application location.
We can save the file on the client machine directly using the following code :

MVC C# Code
public class FileManagementController : Controller{
       
       [System.Web.Mvc.HttpGet]  // Use this annotation attribute to create as a api service(but not 
                                                      as a general mvc controller action with HttpGet attribute )  
        public ActionResult FileDownload(<datatype> fileInfo)
        {
                  ………………   // receive file bytes from some file service based on some fileInfo.
               byte[] filebytes= bytesrecieved; // file in the form of  bytes array.
               return File(  filebytes,      
         System.Net.Mime.MediaTypeNames.Application.Octet, 
        <filename>);
         }
}

Where in the return type as a file, 3 arguments are required to be passed:
Bytes array format of file,
Content Type : Simply writing System.Net.Mime.MediaTypeNames.Application.Octet represents “application/octet-stream” mime-type, and that will handle any format of file download including zipped files,
Filename: filename should be specified including extension . For example : “test.png”,”myImages.zip”. If proper filename will not be supplied, then file will not be downloaded correctly.

On client side, we need to use the following simple code in Javascript to invoke the above “FileDownload” service to make file download on any button/link click

Javascript Code
     var url = <yourdomainurl> + 'FileManagement/FileDownload?fileInfo=' +fileInformation;  
     window.open(url);

Webner Solutions is a Software Development company focused on developing Insurance Agency Management Systems, Learning Management Systems and Salesforce apps. Contact us at dev@webners.com for your Insurance, eLearning and Salesforce applications.

Leave a Reply

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