I have some data in the form of a string. I want to write this data to a file and save the file to the specified path. The path would be specified by opening a save as dialog on the button click. How can this be achieved??
The file is saved into the server initially with this code
string getnote = txtdisplay.Text.Trim();
String filepath = Server.MapPath(#"img\new1.txt");
System.IO.FileStream ab = new System.IO.FileStream(filepath, System.IO.FileMode.Create);
System.IO.StreamWriter Write101 = new System.IO.StreamWriter(ab);
Write101.WriteLine(getnote);
Write101.Close();
Response.ClearContent();
From the server get the file as attachment.Use the following code for save as dialog box for downloading or saving the file. The file will save by default in the download folder. To save to the specified location change the browser settings.
Response.ContentType = "text";
Response.AppendHeader("Content-Disposition", "attachment; filename=new1.txt");
Response.TransmitFile(Server.MapPath("~/img/new1.txt"));
Response.End();
Response.ContentType = "application/octet-stream" (or content type of your file).
Response.AppendHeader("content-disposition", "attachment;filename=" & strFileName)
There is no Save As dialog in ASP.NET.
Remember, your ASP.NET application is running in a browser on a user's computer. You have no access to the user's file system, including the Save As dialog.
However, if you send the user a file, as an attachment, most browsers will display a dialog asking the user whether to save the file or open it. Maybe the user will choose to save it. That's what the example from phoenix does.
You could use a LinkButton (or regular link) and have the url point to a handler (ASHX) that retrieves the data and sends back a response with content disposition set to attachment. Write the data to the response. You'll also need to set up some other headers in the response -- such as content type and length. This would give the document (file) a regular link that could perhaps be bookmarked (if a regular link) in the future so that it can be retrieved again. You'd need to pass enough data in the query string to be able to identify which data is to be downloaded.
if I userstand you correctly, here -
saveFileDialog1.DefaultExt = "*.file";
saveFileDialog1.Filter = "File|*.file|Other File|*.OFile|";
if (saveFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK &&
saveFileDialog1.FileName.Length > 0)
{
WebClient wc = new WebClient();
wc.DownloadFile("http://www.exaple.com/exaplefile", saveFileDialog1.FileName);;
}
Related
I am developing a KnoweldgeBase/Library in which a page lists PDF's and Word Documents associated with the topic selected. These files are uploaded into a folder the URL being "/Interface/AdminUploads/Miscellaneous/FILENAME".
I am listing the files via a table in which each row has an image of the file type, then the file title and then the date published (all created via another page). How can i have the PDF or Word documents opening when i click on the image for the document?
Try This Code.
string filepath ="/Interface/AdminUploads/Miscellaneous/FILENAME"; // Full Path of Pdf.
WebClient client = new WebClient();
Byte[] buffer = client.DownloadData(filepath);
Response.ContentType = "application/pdf";
Response.AddHeader("content-length", buffer.Length.ToString());
Response.BinaryWrite(buffer);
Response.Flush();
Response.End();
You need to put the path in the url of the file.
You need to provide the full path you can ur Server.MapPath to get the full path.
Some useful links
How to open a file by clicking on HyperLink
Try the simple code
Response.Write(string.Format("<script>window.open('{0}','_blank');</script>", "pdflocation/" + "Example.pdf"));
I got it to work via...
System.Diagnostics.Process.Start(#fileLocation);
Running this code in a method on image click and passing in the variable 'fileLocation';
I have some files in a folder on the harddrive, like C:\ExtraContent\ that has some PDF files. This folder is not part of the website. I was able to successfully upload a PDF to this folder using the default ASP.NET FileUploader, no problem.
What I would like to do is, create a hyperlink that links to a PDF in that folder C:\ExtraContent\somePDF.pdf
I am able to get close using a Button with the following code:
protected void Button1_Click(object sender, EventArgs e)
{
WebClient client = new WebClient();
Byte[] buffer = client.DownloadData("C:\ExtraContent\somePDF.pdf");
Response.ContentType = "application/pdf";
Response.AddHeader("content-length", buffer.Length.ToString());
Response.BinaryWrite(buffer);
}
The above works in terms of opening the file. But I can't get this to work with an ASP.NET HyperLink.
The reason I want to use a HyperLink is so that the user can choose to right-click and Save As, to download a copy. If HyperLink controls can only link to relative paths, what can I do to get my desired result?
Note: making the files I'm trying to access part of the site is not practical for us.
Basically allowing access to the folder the way you describe is a real security risk (because it requires hacking at the permissions), isn't trivial and in general should be avoided. The way that you achieve your desired behaviour is something along these lines.
Firstly create a blank aspx or ashx page.
Secondly, either in the Page_Load or ProcessRequest you want to use code along the following lines
string filePath = "c:\\Documents\\Stuff\\";
string fileName = "myPath.pdf";
byte[] bytes = System.IO.File.ReadAllBytes(filePath + fileName);
context.Response.Clear();
context.Response.ContentType = "application/pdf";
context.Response.Cache.SetCacheability(HttpCacheability.Private);
context.Response.Expires = -1;
context.Response.Buffer = true;
context.Response.AddHeader("Content-Disposition", string.Format("{0};FileName=\"{1}\"", "attachment", fileName));
context.Response.BinaryWrite(bytes);
context.Response.End();
I haven't tested this and taken it from my head so it might need some tweeks but the above code should get you on the right track to cause the persons browser to begin downloading the file you provide.
EDIT: I just realized (after rereading your question) your problem was slightly different to what I thought, to get your issue resolved simply make the hyperlink button you are using link to a page that can process the request as described above. IE: An ashx or aspx page
You need to create a hyperlink to a page that acts as a 'proxy' so that the page will return a response that contains the file stream.
You cannot create a link to a file that is not prt of your site.
In my Aspx page I have two buttons, btnGenerateReceipt is for generating receipt and btnAddNew for adding new receord. OnClick event of btnGenerateReceipt I am generating and opening a receipt as below.
protected void onGenerateReceipt(object sender, EventArgs e)
{
try
{
byte[] document = receiptByte;
Response.ClearContent();
Response.ClearHeaders();
Response.Buffer = true;
Response.ContentType = "application/vnd.ms-word";
Response.AddHeader("content-disposition", "inline;filename=" + "Receipt" + ".doc");
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.BinaryWrite(document);
//Response.Flush();
}
}
catch (Exception ex)
{
}
finally
{
//Response.End();
}
}
}
This opens Open/Save/Cancel dialog box, followings are my problems,
I need the word document to open automatically without the dialog box.
My second button's click function doesn't fire after I click btnGenerateReceipt button.
How can I generate&Open PDF file instead of word Doc?
Any idea?
The content sent by the server is handled by the web browser. You can not control from server side code whether the browser opens, saves or asks the user by default, as this is a browser setting.
EDIT
As for the second question about generating a PDF: There are many libraries out there to generate PDFs. However, if you already have the Word file ready, one solution would be to print the Word document to a PDF printer and send the resulting PDF.
Printing the document can be achieved using ShellExecute or the Process class with the verb print, then you could use a PDF printer like PDF-Creator or Bullzip to generate a PDF file.
This is what I'd try instead of "manually" generating the PDF file.
I need the word document to open automatically without the dialog box.
For the answer of the go with #Thorsten Dittmar answer.
My second button's click function doesn't fire after I click btnGenerateReceipt button.
Asp.net uses stateless connection, so do you think your written contents will remain in memory. i think it should not work as per my understanding. create response content and then write it to response and flush it.
How can I generate&Open PDF file instead of word Doc?
To generate pdf reference this. use iTextSharp like library to generate pdf then export/ save them as pdf.
Ref: ASP.NET 4: HttpResponse open in NEW Browser?
Response.AppendHeader("Content-Disposition", "inline; filename=foo.pdf");
You need to set the Content Type of the Response object and add the binary form of the pdf in the header. See this post for details:
Ref: Opening a PDF File from Asp.net page
private void ReadPdfFile()
{
string path = #"C:\Swift3D.pdf";
WebClient client = new WebClient();
Byte[] buffer = client.DownloadData(path);
if (buffer != null)
{
Response.ContentType = "application/pdf";
Response.AddHeader("content-length",buffer.Length.ToString());
Response.BinaryWrite(buffer);
}
}
Ref Links:
ASP.NET 4: HttpResponse open in NEW Browser?
Generate pdf file after retrieving the information
ASP.NET MVC: How can I get the browser to open and display a PDF instead of displaying a download prompt?
I have read some past posts here on how to download a Excel file from a website. So, I have setup the below code:
string path = MapPath(fname);
string name = Path.GetFileName(path);
string ext = Path.GetExtension(path);
string type = "application/vnd.ms-excel";
if (forceDownload)
{
Response.AppendHeader("content-disposition",
"attachment; filename=" + name);
}
if (type != "")
{
Response.ContentType = type;
Response.WriteFile(path);
Response.End();
}
However, I get no download dialog box.
I try this both in IE 8 and FireFox 10.0.2.
The file is there, it's not locked, and it's not set to read only.
I'm not sure were I went wrong.
According to this link, you need to add this line:
strFileName = Path.GetFileName(path);
Response.TransmitFile( Server.MapPath(strFileName) );
This will cause a Open / Save As dialog box to pop up with the filename of SailBig.jpg as the default filename preset.
This of course assumes you're feeding a file that already exists. If you need to feed dynamically generated - say an image [or any file] that was generated in memory - you can use Response.BinaryWrite() to stream a byte array or write the output directly in Response.OutputStream.
EDIT:
Microsoft's MSDN site has a detailed explanation about File Downloading. It includes both samples for Java and .Net applications, the concept is the same:
Get the response.
With the response:
Set the content type to "APPLICATION/OCTET-STREAM" (it means there's no application to open the file).
Set the header to "Content-Disposition", "attachment; filename=\"" + + "\"".
Write the file content into the response.
Close the response.
So, looking at the MSDN ASP.Net file download, you're lacking the 2.3 step. You're just writing the file name to the response.
// transfer the file byte-by-byte to the response object
System.IO.FileInfo fileToDownload = new
System.IO.FileInfo("C:\\downloadJSP\\DownloadConv\\myFile.txt");
Response.Flush();
Response.WriteFile(fileToDownload.FullName);
With this example you will download your file successfully, of course if you can get the file with no problems :).
EDIT 2:
The HTML component used to download any file must be a regular HTML Request. Any ajax request to download a file won't work. Microsoft explains that here. And the main quote:
Its impossible to attach an event before and after a download through javascript. Browser doesn't allow this type of events for security reasons.
You need to send this before the file attachment header:
Response.ContentType = "application/vnd.ms-excel"
See: Export data to excel file from Classic ASP failing
Try adding such HTTP headers
Content-Type: application/force-download
Content-Type: application/vnd.ms-excel
Content-Type: application/download
I hope this is a quick question I hope. I need to write some reports and then have the user prompted to save it to his/her local machine. The last time I did this I wrote a file to the webserver and then sent it to the client via Response object.
to create on the webserver
TextWriter tw = new StreamWriter(filePath);
to send to client
page.Response.WriteFile(path);
The question is, Is there a way to skip the writing of the physical file to to the webserver and go right from an object that represent the document to the response?
You could use the Response.ContentType like this
Response.ContentType = "text/plain";
Response.OutputStream.Write(buffer, 0, buffer.Length);
Response.AddHeader("Content-Disposition", "attachment;filename=yourfile.txt");
This of course works if you want to write a text file. In case you want to write a .doc for example you change the ContentType to "application/msword" etc...
You can.
Try this:
Table oTable = new Table();
//Add data to table.
Response.Clear();
Response.Buffer = true;
Response.ContentType = "application/vnd.ms-excel";
Response.AddHeader("Content-Disposition", "attachment;filename="test.xls"");
Response.Charset = "";
this.EnableViewState = false;
System.IO.StringWriter oStringWriter = new System.IO.StringWriter();
System.Web.UI.Html32TextWriter oHtmlTextWriter = new System.Web.UI.Html32TextWriter(oStringWriter);
0Table.RenderControl(oHtmlTextWriter);
Response.Write(oStringWriter.ToString());
Response.End();
This will give prompt the user to open or save test.xls file.
similarly you can provide other ASP.NET objects in place of Table.
Yes.
page.Response.WriteFile(yourData, 0, yourData.Length);
The exact answer to the question depends on how do you have your report organized (i.e. what is the "object" you're referring to). If you have a single string, you can use Response.Write to just write it. If you need a TextWriter, Response.Output is what you want - that way you can skip writing to the disk and then using WriteFile. Also, if your content happened to be binary, you could use Response.OutputStream for that.
You may also want to set Response.AddHeader("Content-Disposition", "attachment"), if you want the user to see a save file dialog. However, Content-Disposition is not necessarily honored, so the user may still get the report opened directly in the browser. Remember to set headers before you output the actual content!
Also, depending on the format of the report, you may want to set Response.ContentType to something appropriate such as text/plain, text/csv or whatever have you. The correct mime types are listed at the IANA site.