0

我的 wwwroot 文件夹中有一些文件。我想编写一个用户单击输入按钮并下载他想要的文件的代码。因此,在用户选择他的文件之前,文件名是未知的。

我写了这段代码:

配置文件控制器:

    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"}
        };
      }

我的视图组件:

<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>

当我点击下载按钮时,什么也没发生。在跟踪代码中,我没有发现任何问题。文件名正确发送到操作。我认为这是ajax方法的问题。但我没找到。有人能帮我吗?

注意:如果文件名已知,使用以下代码替换输入标签,我可以下载已知文件。

<a asp-action="Download" asp-controller="Profile" asp-route-filename="1.pdf"> download </a>
4

1 回答 1

0

正如我在评论中提到的,我只需要更改 javascript 代码。它适用于 Chrome 和 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>
于 2021-01-03T13:24:42.147 回答