How to implement file download with AJAX and MVC

后端 未结 4 1839
Happy的楠姐
Happy的楠姐 2021-02-07 20:06

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

Example

(javascript)
function DoDownload(start         


        
4条回答
  •  我寻月下人不归
    2021-02-07 20:58

    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.

提交回复
热议问题