Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problem with download file with ajax call in asp.net core

I have some files in my wwwroot folder. I want to write a code that user click on input button and download file that he wants. So filename is unknown until user select his file.

I wrote this code:

Profile Controller:

    public async Task<IActionResult> Download(string filename)
    {
        if (filename == null)
            return Content("filename not present");

        var path = Path.Combine(
                       Directory.GetCurrentDirectory(),
                       "wwwroot", filename);

        var memory = new MemoryStream();
        using (var stream = new FileStream(path, FileMode.Open))
        {
            await stream.CopyToAsync(memory);
        }
        memory.Position = 0;
        return File(memory, GetContentType(path), Path.GetFileName(path));
    }

    private string GetContentType(string path)
    {
        var types = GetMimeTypes();
        var ext = Path.GetExtension(path).ToLowerInvariant();
        return types[ext];
    }

    private Dictionary<string, string> GetMimeTypes()
    {
        return new Dictionary<string, string>
        {
            {".txt", "text/plain"},
            {".pdf", "application/pdf"},
            {".doc", "application/vnd.ms-word"},
            {".docx", "application/vnd.ms-word"},
            {".xls", "application/vnd.ms-excel"},
            {".png", "image/png"},
            {".jpg", "image/jpeg"},
            {".jpeg", "image/jpeg"},
            {".gif", "image/gif"},
            {".csv", "text/csv"}
        };
      }

My view component :

<form>
  <div class="form-group">
      <label> Code :  </label>
      @Html.DropDownList("TopCode", null, htmlAttributes: new { @class ="form-control" })
  </div>
  <script type="text/javascript">
      $(document).ready(function () {
        $('#download').click(function () {
              {
                var fName = $("#TopCode option:selected").val().toString();
                var _url = '@Url.Action("Download", "Profile")';
                $.ajax({
                    type: "POST",
                    url: _url,
                    xhrFields: {
                        responseType: 'blob'
                    },
                    data: {
                        filename: fName,
                    },
                });           
              }
           });
      });
  </script>
  <div class="form-group">
        <input id="download" type="button" value=" download "/>  
  </div>

</form>

when I clicked on download button, nothing happened. In tracing code, I don't find any problem. File name send to action correctly. I think It's a problem from ajax method. but I don't find it. Can someone help me?

Note: If file name was known , with this following code that replace with input tag, I could download the known file.

<a asp-action="Download" asp-controller="Profile" asp-route-filename="1.pdf"> download </a>
like image 463
NedaM Avatar asked Dec 02 '25 09:12

NedaM


1 Answers

As I mentioned in the comments, I only had to change the javascript code. It works in Chrome and Edge

<script type="text/javascript">
  $(document).ready(function () {
    $('#download').click(function () {
          {
            var fName = $("#TopCode option:selected").val().toString();
            var _url = '@Url.Action("Download", "Profile")';
            $.ajax({
                type: "POST",
                url: _url,
                xhrFields: {
                    responseType: 'blob'
                },
                data: {
                    filename: fName,
                },
                success: function (data) {
                    var a = document.createElement('a');
                    var url = window.URL.createObjectURL(data);
                    a.href = url;
                    a.download = 'myfile.pdf';
                    document.body.append(a);
                    a.click();
                    a.remove();
                    window.URL.revokeObjectURL(url);
                }
            });
          }
       });
  });
</script>
like image 88
nicolascolman Avatar answered Dec 04 '25 02:12

nicolascolman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!