Click here to Skip to main content
14,692,401 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
I'm trying to implement file download functionality thru ajax call in MVC. After calling of controller method i always have a "parseerror", can somebody explain me why?

with simple download link in razor it works, but not with ajax. What am I doing wrong here?

What I have tried:

my ajax:

tab.on("click", ".FileDownload", function (e) {

               //$('#uploadStatus').html("ok");
                 var tr = $(this).closest("tr");
                 var id = tr.data("id");

               $.ajax({
                      type: "POST",
                      url: "/File/FileDownload",
                      //contentType: false,
                      //processData: false,
                      //dataType: "json",
                      data: { fileId: id },
                      success: function (data) {
                      $('#uploadStatus').html("ok");
                      },
                       error: function (err) {
                                  alert(err.statusText);
                                              }
         });

     });



and controller:


     [HttpPost]
      public FileResult FileDownload(int? fileId)
      {
       FileDBEntities db = new FileDBEntities();
       tblFile file = db.tblFiles.ToList().Find(p => p.id == fileId.Value);
       return File(file.Data, file.ContentType, file.Name);
      }
Posted
Updated 6-Aug-20 9:05am
Comments
F-ES Sitecore 7-Aug-20 5:54am
   
As you've already found out, you can't download files using ajax. When using ajax everything happens in javascript and js doesn't have write access to your hard drive so while it can process the request it can't do anything meaningful with the results. To save the file you need the browser's file downloader to kick in and that will only happen when the browser makes a request that has a download as the response, you can't instigate that process via js.

1 solution

tab.on("click", ".FileDownload", function (e) {

    //$('#uploadStatus').html("ok");
    var tr = $(this).closest("tr");
    var id = tr.data("id");

    window.location = window.location.origin + '/File/FileDownload?fileId=' + id;

});

[HttpGet]
    public FileResult FileDownload(int? fileId)


solved!
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900