Click here to Skip to main content
14,697,262 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
In My Web application,

I want download the file from ajax call.

reference:Call HTTPhandler from jQuery, Pass data and retrieve in JSON format[^]

here i am unable to download file, see my code below

In Handler.ashx file

public void ProcessRequest(HttpContext context)
        {

            string PPTOutputPath = context.Request.QueryString["DownLoadFileName"];
            PPTOutputPath = PPTOutputPath.Replace(",", "\\");
            FileInfo PPTFileNewfile = new FileInfo(PPTOutputPath);
            long sz = PPTFileNewfile.Length;
            context.Response.ClearContent();
            context.Response.ContentType = MimeType(Path.GetExtension(PPTOutputPath));
            context.Response.AddHeader("Content-Disposition", string.Format("attachment; filename = {0}", System.IO.Path.GetFileName(PPTOutputPath)));
            context.Response.AddHeader("Content-Length", sz.ToString("F0"));
            context.Response.TransmitFile(PPTOutputPath);
            context.Response.Flush();
            context.Response.End();
        }


My ajax call

function CallHandler(PPTOutputPath) {
            $.ajax({
                type: 'POST',
                url: "MyHandler.ashx?DownLoadFileName=" + PPTOutputPath,
                
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                data: "{'imageData': '" + PPTOutputPath + "'}",
                responseType: "json",
                success: OnComplete,
                error: OnFail
            });
            return false;
        }

function OnComplete(result) {
        alert('Ajax success');
}
function OnFail(result) {
    alert('Ajax failed');

}


i am getting ajax failed message and file not down loading
Posted
Updated 11-Mar-14 2:06am
v3

1 solution

You can not write file on client without browser interaction(as actual client for server is browser) due to security reasons, so in your ajax call it would be better if you will reload your page and in page_load you write download code or call a function where you have kept your file download code. Suppose you are downloading a pdf file.

function CallHandler(PdfFileName) {
var urlCur = window.location+"?DownLoadFileName=" + PdfFileName;
window.location.href=urlCur;
}

in your page load write download code:

string FileName= Request.QueryString["DownLoadFileName"];
if (!string.IsNullOrEmpty(FileName))
{
string pathOfFolder = "here put folder path where this file is";//Or you can use server.MapPath("path of your file")
string fileToDownload = pathOfFolder + FileName;
if (File.Exists(fileToDownload))
{
try
{
using (FileStream fileStream = System.IO.File.OpenRead(fileToDownload))
{
MemoryStream memoryStream = new MemoryStream();
memoryStream.SetLength(fileStream.Length);
fileStream.Read(memoryStream.GetBuffer(), 0, (int)fileStream.Length);
byte[] bytes = memoryStream.ToArray();
memoryStream.Close();
Response.Clear();
Response.AddHeader("Content-Disposition", "attachment; filename=" + FileName);
Response.ContentType = "application/pdf";
Response.Buffer = true;
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.BinaryWrite(bytes);
Response.Flush();
}
}
finally
{
System.IO.File.Delete(fileToDownload);
}
}
}
   

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