vendredi 22 novembre 2019

how to allow file download in asp.net from dynamically generated table

I am using elasticsearch to query in index of PDFs on a asp.net mvc app. When I get the result I would like the user to be able to click the returned filename to download that file. Researching how to enable this functionality has returned plenty of results but none seem to work for me. I would simply like the user to be able to click on the filename and have the file download for them. I am using the below code.

To generate the dynamic table with search results

var row = $("<tr><th>" + "Search Results" + "</th><th>" + "File Name" + "</th>");
$("#myTable").append(row);
for (var i = 0; i < response.datasend.length; i++) {
var pos = response.datasend[i].Attachment.Content.indexOf(obj.searchterm);
var row = $("<tr><td>" + response.datasend[i].Attachment.Content.slice((pos - 100), (pos + 100)) + "</td><td><a href=# id=fileName>"
+ response.datasend[i].filename + "</a></td></tr>");
$("#myTable").append(row);
}

To detect the requested filename and call the function to start the download process

    var table = document.getElementById("myTable");
    table.addEventListener("click", function(e) {
    if (e.target && e.target.id == "fileName")
    {
        var apiUrl = "/AllSearch/Download";
        var obj = {};
        obj.searchterm = e.target.innerHTML;
        var params = e.target.innerHTML;
        $.ajax({
            contentType: 'application/json',
            url: apiUrl,
            dataType: "json",
            data: {fileName: obj.searchterm},
            success: function(data) {
                alert("success");
            },
            error: function (xhr, err) {
                alert("ready state: " + xhr.readyStat + " " + xhr.status);
            }
        });
    }
});

To start download the file

public ActionResult Download(string fileName)
        {
            string filename = fileName;
            string filePath = @"C:;at\to\file\Documents\" + fileName;
            byte[] filedata = System.IO.File.ReadAllBytes(filePath);
            string contentType = MimeMapping.GetMimeMapping(filePath);

            var cd = new System.Net.Mime.ContentDisposition
            {
                FileName = filename,
                Inline = true,
            };

            Response.AppendHeader("Content-Disposition", cd.ToString());

            return File(filedata, contentType);
        }

The Download function is from Returning a file to View/Download in ASP.NET MVC but it returns an error when I run it. Not sure what I am missing here. Any help is appreciated




Aucun commentaire:

Enregistrer un commentaire