I am working on an image gallery, and on the browse image module, I have a download icon. I need it to behave as a download button. When the user clicks on it, they should be presented with save file dialog, or the file should be downloaded using their default browser download set-up.
I tried many ways, but no luck.
The download Icons appear in a Modal-popup and hence all code is wrapped inside UpdatePannel
These images are of different formats (jpeg, gif, tif, psd)
Look at http://www.codeproject.com/Articles/74654/File-Download-in-ASP-NET-and-Tracking-the-Status-o or Best way to stream files in ASP.NET
Finally sorted out with :
A) To download a file at Client Location :
public void downloadFile(string fileName, string filePath)
{
Response.ContentType = "application/octet-stream";
Response.AddHeader("Content-Disposition", string.Format("attachment; filename=\"{0}\"", fileName));
Response.WriteFile(filePath + fileName);
}
B) Since the function triggering controls(imgDownload, imgDownloadPsd) are wrapped under async call : Add this to Page Load :
protected void Page_Load(object sender, EventArgs e)
{ ScriptManager.GetCurrent(this.Page).RegisterPostBackControl(imgDownload);
ScriptManager.GetCurrent(this.Page).RegisterPostBackControl(imgDownloadPsd);
}
Related
I have the remote computer, it name is A11
and a image file name is A22
i try my code use aspnet run IE11 , IE11 can show image ,but chrome can't show.
my code is same , as follow
protected void Page_Load(object sender, EventArgs e)
{
Image2.ImageUrl = #"file://A11/A2222.jpg";
Image1.ImageUrl = #"\\A11\\A2222.jpg";
}
i try other method
FileInfo fi = new FileInfo(#"\\A11\\A2222.jpg");
Response.AddHeader("Content-Disposition", "inline;Filename=" + #"\\A11\\A2222.jpg");
Response.AddHeader("Content-Length", fi.ToString());
other method:
clear Cache
open image display option
but it is not working for chrome, it still no show my image
how can i do ?
ps.
chrome ver.78.0.3904.108
Most modern browsers doesn't allow local images to be shown unless you open a static html file from local disk. Since you are using asp.net webforms I will assume you are not doing this and you might need to rethink your approach.
If you simply need to be able to use images from a fileshare I would instead make a virtual directory on IIS and use this instead, so links becomes /virtualdirectory/somefile.jpg for example.
I have created a interface where user will select and upload image. But how can i rename and save image in server folder(images), and display it again on my image gallery page. My website is developed in asp.net c#.Suggest me some ideas or links to refer.
upload button click code below:
protected void Button1_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
string fileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
FileUpload1.PostedFile.SaveAs(Server.MapPath("~/uploads/") + fileName);
Response.Redirect(Request.Url.AbsoluteUri);
}
}
Thanks.
You will need, obviously, a folder somewhere in the website's directory. The user who is running the application pool for the web application will need read/write access to it. Depending on your needs, you may not want this folder to be browsable directly by users (other than the user running the application pool).
You will need to store the new file path somewhere (database, XML file, flat text, etc.) so when the user requests to see the image, you will open this file, and return it in the response stream as its proper type (JPG, GIF, BMP, etc.) so the user is prompted to open it or save it.
For Rename and save image in server folder try below code : -
//Get Filename from fileupload control and rename it
string filename = ((DateTime.Now.ToString().Replace("/", "-")).Replace(":", "")).Replace(" ", "_") + "_" + ((Path.GetFileName(FileUpload1.PostedFile.FileName)).Replace(".",".")).Replace(" ","");
FileUpload1.SaveAs(Server.MapPath("~/uploads/" + filename));
I have a page where I'm simply trying to write a pdf to the screen. Here's what I'm doing:
protected void ViewPDF(string url)
{
Response.Clear();
Response.ClearContent();
Response.ClearHeaders();
Response.ContentType = "application/pdf";
Response.TransmitFile(url);
Response.Flush();
Response.End();
}
This works in every browser and OS except for Firefox on Mac. Instead of displaying the pdf file in the browser, the browser opens the dialog to download the file, where you can Open it or Save it.
I've also tried this:
protected void ViewPDF(string url)
{
Response.Clear();
Response.ContentType = "application/pdf";
string path = Server.MapPath(url);
byte[] data = File.ReadAllBytes(path);
Response.BinaryWrite(data);
Response.End();
}
And I get the same result.
Anyone know how to fix this?
The browser needs to be able to render any given file format. Firefox (for Mac) does not include a PDF renderer out of the box. It's that simple.
See http://support.mozilla.org/en-US/kb/view-pdf-files-firefox-without-downloading-them.
You can try changing the content disposition header. There is a full discussion in this post:
Content-Disposition:What are the differences between “inline” and “attachment”?
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?