How to implement file download with AJAX and MVC

后端 未结 4 1774
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:51

    What I ended up doing is calling my controller from my javascript like:

    var url = "/mycontroller/GetFile?startDate=" + $("#mydate").val() + etc...
    
    window.location = url;
    

    mycontroller.cs

     public void GetFile(DateTime startDate) 
    {
    
    }
    

    My original concern was with the date parameters. I didnt want to have to parse it.

    0 讨论(0)
  • 2021-02-07 20:55

    Using the ActionLink helper, you can pass multiple params to your controller:

    HtmlHelper.ActionLink(
        string linkText, 
        string actionName, 
        string controllerName, 
        object routeValues, 
        object htmlAttributes
    )
    

    So in your case:

    @Html.ActionLink("Download file", "GetFile", "MyController", new { startDate = "##" }, new { id="mydownloadlink" })
    

    Using jQuery you can change the value of the startDate in the link with the content of your date picker or textbox.

    $("#mydownloadlink").attr("href").replace("##", $("#yourdatetexbox").val);
    

    Then, in your controller, just use one of the other answers here, about FileResult.

    Hope this help you...

    0 讨论(0)
  • 2021-02-07 20:56

    Your controller action method should return a FileResult instead of void. And there is no need to do this via AJAX - in fact, you don't want to do this with AJAX. You'll need the browser involved so it knows to provide a download dialog for the user.

    See these links:

    Handling an ASP.NET MVC FileResult returned in an (jQuery) Ajax call

    File download in Asp.Net MVC 2

    I hope this helps.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题