Jean Paul Olvera Jean Paul Olvera - 6 days ago 9
ASP.NET (C#) Question

Return datatbase stream file to WebPage from ASHX

I successfully could save a binary stream field to database (pdf, jpg, etc) and return it to my Webpage like this in a ASP.net Gridview:

<asp:HyperLinkField DataNavigateUrlFields="ID" DataNavigateUrlFormatString="~/Formularios/file.ashx?ID={0}" HeaderText="Documento"
DataTextFormatString="{0}" Target="_top" Text="Download document" />


and in file.ashx

public void ProcessRequest(HttpContext context)
{

using (OficiosRecibidosDataContext db = new OficiosRecibidosDataContext())
{
int value = Convert.ToInt32(context.Request.QueryString["ID"]);

OficiosRecibidosDocumentos padDoc = db.OficiosRecibidosDocumentos.SingleOrDefault(p => p.Id == value);


if (padDoc == null) return;

string strMIME = "";

switch (padDoc.Extension.Trim())
{
case ".jpg":
strMIME = "image/jpeg";
break;
case ".xls":
strMIME = "application/vnd.ms-excel";
break;
case ".xlsx":
strMIME = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
break;
case ".doc":
strMIME = "application/msword";
break;
case ".docx":
strMIME = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
break;
case ".pdf":
strMIME = "application/pdf";
break;
default:
strMIME = "application/octet-stream";
break;

}


context.Response.Clear();
context.Response.AddHeader("content-disposition", "attachement filename=" + padDoc.NombreArchivo.Trim() + padDoc.Extension.Trim());
context.Response.ContentType = strMIME;
context.Response.BinaryWrite((byte[])padDoc.Contenido.ToArray());
context.Response.End();

}

}

public bool IsReusable {
get {
return false;
}
}


This is my record

enter image description here

Everything works fine but when im using Firefox and click ond Download Document an "open /save as" dialog pop up appears and if I select "save/as" the file that is downloaded is called "file.ashx". where I am wrong? Is not context.Response.AddHeader suppose to be where I indicate the name and extension of the output file?

Answer

Try using

context.Response.AddHeader("content-disposition", "attachment; filename=\"" + padDoc.NombreArchivo.Trim() + padDoc.Extension.Trim() + "\"");

First of all, you spelled attachment wrong.

Second, it needs a ; between it and the filename.

And not related to your error, but if your filename has a space in it, it would give a truncated filename.