I have some files stored on my machine. When a user wants to generate a link the page should generate a hyperlink. This hyperlink can be used by any other user so as to download the file
Have a LinkButton and for the click event do the following
your aspx file will have the following
<asp:LinkButton runat="server" OnClick="btnDownload_Click" Text="Download"/>
Your code behind will have the following
protected void btnDownload_Click(object sender, EventArgs e)
{
try
{
var fileInBytes = Encoding.UTF8.GetBytes("Your file text");
using (var stream = new MemoryStream(fileInBytes))
{
long dataLengthToRead = stream.Length;
Response.Clear();
Response.ClearContent();
Response.ClearHeaders();
Response.BufferOutput = true;
Response.ContentType = "text/xml"; /// if it is text or xml
Response.AddHeader("Content-Disposition", "attachment; filename=" + "yourfilename");
Response.AddHeader("Content-Length", dataLengthToRead.ToString());
stream.WriteTo(Response.OutputStream);
Response.Flush();
Response.Close();
}
Response.End();
}
}
catch (Exception)
{
}
}
you can direct link the hyperlink with the file if you know the address but this is limited by the browser. eg. if pdf reader is installed on the client then the pdf will not be downloaded instead it will be shown. A good solution would be to have a seperate page for downloading files. just pass filename in querystring and in the pageload event just outpit the file in response stream.This way you can use url say dwnld.aspx?filename.ext
Now you can generate urls via the above logic.
Related
I am saving the path of the file in database and file is in server folder and the gridview control is used to show the files from the database. i need to download the selective files from the gridview using download button Click event.
Here is my code:
protected void btn_download_Click(object sender, EventArgs e)
{
using (ZipFile zip = new ZipFile())
{
zip.AlternateEncodingUsage = ZipOption.AsNecessary;
zip.AddDirectoryByName("records");
foreach (GridViewRow row in GridView1.Rows)
{
if ((row.FindControl("chkSelectoptn") as CheckBox).Checked)
{
string filePath = (row.FindControl("lblFilePath") as Label).Text;
zip.AddFile(filePath, "records");
}
}
Response.Clear();
Response.BufferOutput = true;
string zipName = String.Format("Zip_{0}.zip", DateTime.Now.ToString("yyyy-MMM-dd-HHmmss"));
Response.ContentType = "application/zip";
Response.AddHeader("content-disposition", "attachment; filename=" + zipName);
zip.Save(Response.OutputStream);
Response.End();
}
}
I am using a label lblFilePath to give the path of the file name which we had store in the database.
But "FileNotFoundException" occurs.
Please suggest.
I have stored binary data into a db.
When I'm fetching and trying to download same pdf file I'm unable to do it.
Below is my code snippet:
protected void grdDownload_Command(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Download")
{
int index = Convert.ToInt32(e.CommandArgument);
DataTable dtFilterData = `enter code here`GetPDFFile("D", Convert.ToString(index));
Response.Clear();
Response.Buffer = true;
Response.ContentType = dtFilterData.Rows[0]["ContentType"].ToString();
Response.AddHeader("content-disposition", "attachment;filename=" + dtFilterData.Rows[0]["Name_File"].ToString()); // to open file prompt Box open or Save file
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.BinaryWrite((byte[])dtFilterData.Rows[0]["FileData"]);
Response.End();
}
}
Finally i have resolved this issue. We need to add update panel for link button inside the Item template.
Adding Postback Trigger has resolved this issue.
I am downloading a pdf file in my project. I want to let the user decide where to download the File. Quick help is helpful.
Thanks
try this:
It will display a dialog box in the browser and the user will select on where to save the file
protected void DownloadFile_Click(object sender, EventArgs e)
{
String Filepath;
System.IO.FileInfo file = new System.IO.FileInfo(Filepath); // full file path on disk
Response.ClearContent(); // Clear previous content
Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
Response.AddHeader("Content-Length", file.Length.ToString());
Response.ContentType = "application/pdf";
Response.TransmitFile(file.FullName);
Response.End();
}
You haven't specified how your application is serving this PDF file, but assuming that you have some WebForm which is streaming it to the Response, you should set the Content-Disposition header as attachment in order to force the Save As dialog in the browser.
For example:
protected void Download(object sender, EventArgs e)
{
Response.ContentType = "application/pdf";
Response.AddHeader("Content-Disposition", "attachment; filename=example.pdf");
Response.WriteFile(#"c:\work\example.pdf");
}
I want to return a xml file to a client, and THEN perform my logic.
I try to use Response.Flush(), but it doesn't work correctly for me.
My code:
protected void Page_Load(object sender, EventArgs e)
{
string arg1= this.Request["arg1"];
string arg2= this.Request["arg2"];
string arg3= this.Request["arg3"];
var doc = new XmlDocument();
XmlNode responseNode = doc.CreateElement("response");
doc.AppendChild(responseNode);
var messageNode = responseNode.AppendChild(doc.CreateElement("message"));
messageNode.InnerText = "Your request is being processed";
Response.Clear();
Response.ContentType = "text/xml";
Response.ContentEncoding = System.Text.Encoding.UTF8;
doc.Save(Response.Output);
Response.Flush(); // I want to display xml in this moment but it doesn't work
LogicManager manager = new LogicManager();
manager.DoSth(arg1, arg2, arg3);
Response.End();
}
Response.End();
Generally, it is a bad idea to be using Response.End() in your code.
From the source: This method is provided only for compatibility with ASP—that is, for compatibility with COM-based Web-programming technology that preceded ASP.NET. If you want to jump ahead to the EndRequest event and send a response to the client, it is usually preferable to call CompleteRequest instead.
Given this info, instead of this:
Response.Flush(); // I want to display xml in this moment but it doesn't work
LogicManager manager = new LogicManager();
manager.DoSth(arg1, arg2, arg3);
Response.End();
do this:
Response.Flush(); // I want to display xml in this moment but it doesn't work
Response.CompleteRequest();
LogicManager manager = new LogicManager();
manager.DoSth(arg1, arg2, arg3);
// here you might want to make sure that no other page handlers are executed
The following method, based on code in this question, shows a file download dialog box in the browser, but then the download never starts (it stays at 0%):
protected void lnkExport_Click(object sender, EventArgs e) {
var bytes = Encoding.ASCII.GetBytes(SelectRecords()); //Data to be downloaded
Response.Clear();
Response.ContentType = "application/vnd.ms-excel";
Response.AddHeader("Content-Disposition", "attachment; filename=\"test.xls\"");
using (var stream = new MemoryStream(bytes)) {
Response.AddHeader("Content-Length", stream.Length.ToString());
stream.WriteTo(Response.OutputStream);
}
}
Any idea what's up?
Your code worked fine for me but you may want to try adding this as the last line of your click handler:
Response.End();