Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement file download with AJAX and MVC

I would like to provide a file download operation by using the jQuery AJAX call with some params under MVC

Example

(javascript)
function DoDownload(startDate) {

  $.ajax({ 
     url:"controller/GetFile/",
     data: {startDate:startDate}
     ...
  });

}

C# Controller Code

 public void GetFile(string startDate) {

  var results = doQueryWith(startDate);

   // Create file based on results
   ....
   // How do I tell the server to make this a file download??
 }

I typically would just make my file download a link such as:

<a h r e f="mycontroller/getfile/1"/>Download</a>

but in the case above the date will be dynamic.

If I don't use ajax, what would be a preferred way to pass in the params to the MVC controller using javascript?

Example:

window.location  = "mycontroller/GetFile/" + $("#fromDate").val();

assuming the date is 12-25-2012

Would this produce

mycontroller/GetFile/12/25/2012

would MVC treat this as three params?

like image 243
Arcadian Avatar asked Dec 30 '12 02:12

Arcadian


People also ask

Can we download file using Ajax?

Downloading PDF File on Button Click using jQueryInside the DownloadFile JavaScript function, the URL of the File is passed as parameter to the jQuery AJAX function. Inside the jQuery AJAX function, using the XmlHttpRequest (XHR) call, the PDF file is downloaded as Byte Array (Binary Data).


1 Answers

You can use the File method of controller class to return a file back to the browser.

The below sample returns a pdf file.

public ActionResult GetFile(int id)
{
  var fileInfo=repositary.GetFileDedetails(id);
  var byteArrayOFFile=fileInfo.FileContentAsByteArray();
  return File(byteArrayOFFile,"application/pdf","yourFriendlyName.pdf");
}

Assuming repositary.GetFileDedetails method returns the details of the file from the id.

You may also return the file from a physical location(a path) or a stream. Check all the overloads of the File method and use appropriate one.

This has nothing to do with ajax. this is normal GET request over a browser.

like image 181
Shyju Avatar answered Oct 05 '22 08:10

Shyju