'How to download files on client side from physical path in ASP.NET

i have a generic controller which I call using AJAX. It recieves the path from a file

(for example: C:\\Control_Ventas\\2022\\2022_03\\13032022\\58_13032022\\hola.txt)

In this case is a txt but it could be a pdf or a excel document. I tried to make it work with this code, but it didnt worked.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace Dbventas
{
    /// <summary>
    /// Descripción breve de FileDownloadHandler
    /// </summary>
    public class FileDownloadHandler : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            
            HttpResponse response = HttpContext.Current.Response;
            string filePath = context.Request.Form.Get("path");
            response.Clear();
            response.ClearContent();
            response.ClearHeaders();
            response.Buffer = true;
            byte[] data = System.IO.File.ReadAllBytes(@filePath);
            response.BinaryWrite(data);
            response.End();
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}

Edit: this is de AJAX call and the code that I modified. Now the file is sent to the client, but i dont know how to build the file again.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace Dbventas
{
    /// <summary>
    /// Descripción breve de FileDownloadHandler
    /// </summary>
    public class FileDownloadHandler : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
         
            HttpResponse response = HttpContext.Current.Response;
            string filePath = context.Request.Form.Get("path");
            filePath = filePath.Replace("/", @"\");
            byte[] data = System.IO.File.ReadAllBytes(@filePath);
            response.Clear();
            response.AddHeader("Content-Length", data.Length.ToString());
            response.AddHeader("Content-Disposition", "attachment;filename=FILENAME");
            response.OutputStream.Write(data, 0, data.Length);
            response.Flush();
            response.End();
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}

AJAX call

function downloadFile(id) {
        
        var fd = new FormData();
        fd.append("nombre", document.getElementById(id).dataset.filename);
        fd.append("path", document.getElementById(id).dataset.path);
        console.log(fd);
        
        try {
            $.ajax({
                url: 'FileDownloadHandler.ashx',
                type: "POST",
                contentType: false, // Not to set any content header  
                processData: false, // Not to process data  
                data: fd,
                success: function (result) {
                    console.log(result);
                },
                error: function (err) {
                    console.log("Error");
                    alert(err.statusText);
                }
            });
        } catch (exception) {
            console.log("ERROR"); alert(exception);
        }
    }

Thanks for reading!



Solution 1:[1]

I've had a case like this, but in vb.net

I'm change :

response.AddHeader("Content-Length", data.Length.ToString());
            response.AddHeader("Content-Disposition", "attachment;filename=FILENAME");
            response.OutputStream.Write(data, 0, data.Length);
            response.Flush();
            response.End();

To:

Dim stream As MemoryStream = New MemoryStream(Pck.GetAsByteArray())
            Response.AppendHeader("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
            Response.AppendHeader("Content-Disposition", "attachment; filename=Filename.xlsx")
            Response.BinaryWrite(stream.ToArray())
            Response.End()

maybe you can search code similar like above in c#

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Malik Ilman