I have used a Gridview Control to display the contents of a directory in asp.net webforms.
The contents are filtered to display only PDF files.
I also have a Button inside a TemplateField. On the click of the button the user should be able to download and save the PDF file.
The columns displayed in the Gridview are File Name, Modified Date and Size.
How can I program the Button click to download and save the PDF file?
I have a function that performs a file download.
public static void DownloadFile(string FilePath, System.Web.HttpResponse response)
{
System.IO.FileInfo file = new System.IO.FileInfo(FilePath);
if ((file.Exists))
{
response.Clear();
response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
response.AddHeader("Content-Length", file.Length.ToString());
response.ContentType = "application/octet-stream";
response.WriteFile(file.FullName);
response.End();
response.Close();
file = null;
}
}
The FilePath parameter is the physical path, so if you have the virtual path (e.g. ~/Folder/file.pdf) might need to use the Server.MapPath(...) function to call the function.
In your Button click event, write the following code.
protected void Button1_Click(object sender, EventArgs e)
{
Response.ContentType = "Application/pdf";
Response.AppendHeader("Content-Disposition", "attachment; filename=Your_Pdf_File.pdf");
Response.TransmitFile(Server.MapPath("~/Files/Your_Pdf_File.pdf"));
Response.End();
}
Related
using the following code I'm trying to download pdf file from server path but after clicking on download button file not download but the code gets file name and file path.
I think I'm missing something in code so, please help me out
Thank you in advance..
code is :
protected void btn_Download_Template_Click(object sender, EventArgs e)
{
string mainPath = "";
string fileName = "Self_Declaration.pdf";
mainPath = Server.MapPath("~/Template/Self_Declaration.pdf");
FileInfo file = new FileInfo(mainPath);
if (file.Exists)
{
Response.Clear();
Response.ClearHeaders();
Response.ClearContent();
Response.AddHeader("content-disposition", "attachment; filename= ~/Template/Self_Declaration.pdf");
Response.AddHeader("Content-Type", "application/pdf");
Response.ContentType = "application/pdf";
Response.WriteFile(file.FullName);
Response.End();
}
else
{
Response.Write("This file does not exist.");
}
}```
Well I don't have enough reputation points to put this in the comment section, but I think your question has already been answered here
I am using aspose to find specific text and highlight it and open that excel file in browser.
Problem is it find and highlight and excel file get downloaded, which i dont want i want to show the contents of excel in browser.
For pdf this works perfectly fine, opens up in browser
PDF code -
if (docBytes != null)
{
Response.ContentType = "application/pdf";
Response.AddHeader("content-length", docBytes.Length.ToString());
Response.BinaryWrite(docBytes);
}
Here is my code - (excel) - Does not open excel in browser
using (MemoryStream docStream = new MemoryStream())
{
workbook.Save(docStream, Aspose.Cells.SaveFormat.Xlsx);
docBytes = docStream.ToArray();
}
if (docBytes != null)
{
Response.ContentType = "application/vnd.ms-excel";
Response.AppendHeader("content-disposition",
"attachment; filename=" + "yourExcelFileName.xlsx");
Response.AddHeader("content-length", docBytes.Length.ToString());
Response.BinaryWrite(docBytes);
Response.End();
}
Look at these lines.
Response.AppendHeader("content-disposition",
"attachment; filename=" + "yourExcelFileName.xlsx");
The "attachment" part tells the browser that this file should be downloaded and not displayed in the browser.
Remove that and it should work (in browser that can host Excel at least, so Internet Explorer and possibly Edge).
Response.AppendHeader("content-disposition", "filename=yourExcelFileName.xlsx");
You can read about the attachment parameter over on MDN.
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition#Syntax
I think you may try the line instead if it makes any difference:
Response.AppendHeader("content-disposition",
"inline; filename=" + "yourExcelFileName.xlsx");
i need to download images that i stored in folder in asp.net web application name as uploads
i got a function that should download this as
private void downloadAnImage(string strImage)
{
Response.ContentType = "image/jpg";
Response.AppendHeader("Content-Disposition", "attachment; filename=" + strImage);
Response.TransmitFile(strImage);
Response.End();
}
and i call this function from link button as
protected void lnkDwnSlc_Click(object sender, EventArgs e)
{
if (Session["slc_filepath"] != null)
{
string path = Server.MapPath(Session["slc_filepath"].ToString());
downloadAnImage(path);
}
}
where Session["slc_filepath"] is path stored in session
but after running this code file/image is not downloading and I got no error about why file is not downloading. And I checked file path by using breakpoint , it is correct,
I search a lot form google but i can't understand where I missed something.
EDIT:
on page load event i pull records from table there i saved path of file and in session i store it like
Session["slc_filepath"] = dt.Rows[0]["UploadSLC"].ToString();
where UploadSLC is column name of table where i store path of image
and in database string is looking as
~\uploads\ab071770-473a-4e1a-8cfc-addeccf565d5.jpg
I found answer after a long searching but a hint i got is from my junior in my team i really appreciate it, i just added
ScriptManager scriptManager = ScriptManager.GetCurrent(this.Page);
scriptManager.RegisterPostBackControl(this.lnkDwnSlc);
in pageLoad event because i am using update panel and script manager in my aspx page and bootstrap for design so it stopped functionality
after doing so it works like a charm,
thanks all of your efforts and support,
Try this:
private void downloadAnImage(string strImage)
{
Response.Clear();
Response.ContentType = "image/jpg";
Response.AppendHeader("Content-Disposition", "attachment; filename=" + strImage);
Response.TransmitFile(strImage);
Response.Flush();
Response.End();
}
Happy to help you!
I suggest to troubleshoot the issue where it came from.
Try a hardcoded path (to make sure, you are passing the correct path)
//try forward or back slash, make sure the file exists
string path = Server.MapPath("~/uploads/ab071770-473a-4e1a-8cfc-addeccf565d5.jpg");
Try this:
private void downloadAnImage(string strImage)
{
Response.ContentType = "image/jpg";
Response.AppendHeader("Content-Disposition", "attachment; filename=" + strImage);
Response.TransmitFile(strImage);
Response.Flush();
Response.End();
}
Make sure there's no javascript error that is being thrown on the client side.
Please correct your path of image while binding from database
like "~/Image/images.png ".
PFB of my snippet code you may supposed to get solution.
protected void Page_Load(object sender, EventArgs e)
{
Session["slc_filepath"] = "~/Image/images.png";
}
protected void LinkButton1_Click(object sender, EventArgs e)
{
string path = Server.MapPath(Session["slc_filepath"].ToString());
downloadAnImage(path);
}
private void downloadAnImage(string strImage)
{
Response.ContentType = "image/jpg";
Response.AppendHeader("Content-Disposition", "attachment; filename=" + strImage);
Response.TransmitFile(strImage);
Response.End();
}
Use an ashx Handler like this http://www.intstrings.com/ramivemula/asp-net/how-to-download-files-from-server-to-client-using-a-generic-handler/
Then send by ajax a window.Open to the new ashx.
I have an ImageButton control within a ListView which, when clicked, should download the image with the right ID.
Here's the ImageButton ASPX:
<asp:ImageButton runat="server" ID="ibtDownloadImage" ImageUrl="img/downloadIcon.png" OnClick="ibtDownloadImage_OnClick" CommandArgument='<%# Convert.ToString(Eval("ID"))+Convert.ToString(Eval("FileExtension")) %>' />
As you can see, when it is clicked, it executes the "ibtDownloadImage_OnClick" method and sets the command argument to the ID plus the FileExtension (for example, 1.jpg, which is the name of the image).
My C# code for the ibtDownloadImageOnClick is:
protected void ibtDownloadImage_OnClick(object sender, EventArgs e)
{
ImageButton img = (ImageButton)sender;
string file = img.CommandArgument;
String imgURLtoDownload = #"img/uploads/"+file;
Response.AddHeader("Content-Disposition", "attachment; filename=" + imgURLtoDownload);
}
When I click the ImageButton control, it downloads a file called "img-uploads-1.jpg" (without the speech marks), so it seems to be taking what I intended to be the filepath as part of the name, and replacing the / with -...
Any ideas on how to fix this? It seems like it should be a simple solution.
I've run debugging with a breakpoint on the Response.AddHeader line and imgURLtoDownload's content is img/upload/1.jpg (as it should be)..
You can read file content as binary, let say you have function for this , that takes file name get byte array as binary content, and that function name GetFileContent(Filepath). Then you can use that function to write content to response and yet specify custom path.
ImageButton img = (ImageButton)sender;
string file = img.CommandArgument;
String imgURLtoDownload = #"img/uploads/"+file;
byte[] data= GetFileContent(Server.MapPath(imgURLtoDownload));
Response.Clear();
Response.AddHeader("Content-Disposition", "attachment; filename=" + file);
Response.ContentType = System.Web.MimeMapping.GetMimeMapping(Server.MapPath(imgURLtoDownload));
Response.BinaryWrite(data);
Response.End();
public byte[] GetFileContent(string Filepath)
{
return System.IO.File.ReadAllBytes(Filepath);
}
I am allowing users to download either a PDF file or a zip file, and when they try to download the file, I want the appropriate file to be downloaded according to its type. For example: if the uploaded file is PDF, then it should be downloaded as a PDF; if the uploaded file is zip, then it should downloaded as a zip file.
I have written this code and I am able to download the files as PDF using "output.pdf" in the append header, but don't know how to give two options to append header so that it downloads the file according to its type.
protected void gridExpenditures_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Download")
{
Response.Clear();
Response.ContentType = "application/octet-stream";
Response.AppendHeader("content-disposition", "FileName=" + e.CommandArgument + "output.pdf");
Response.TransmitFile(Server.MapPath("~/Match/Files/") + e.CommandArgument);
Response.End();
}
}
You can use a utility like this one to detect the content type of the file in question, then render the header like this:
protected void gridExpenditures_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Download")
{
var filePath = Server.MapPath("~/Match/Files/") + e.CommandArgument;
var contentType = MimeTypes.GetContentType(filePath);
if (string.IsNullOrEmpty(contentType))
{
contentType = "application/octet-stream";
}
Response.Clear();
Response.ContentType = contentType;
Response.AppendHeader("content-disposition", "FileName=" + e.CommandArgument);
Response.TransmitFile(filePath);
Response.End();
}
}
You need to set your content type to the appropriate application, instead of octet-stream.
For example I had this to open PowerPoint:
application/vnd.openxmlformats-officedocument.presentationml.presentation
Look up your file type in this link:
http://en.wikipedia.org/wiki/Internet_media_type
I store the uploaded content type in my database for each file.