I want to download an Excel sheet to my specific location not to Download folder.
I tried below code. Then the file is download to the "Download" folder. I need to download this file to a given file path.
string filepath = "D:\";
string strDownloadableFilename = "Test.xlsx"
Using (MemoryStream stream = ExportExcel()){
Response.Clear();
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}", strDownloadableFilename));
stream.WriteTo(Response.OutPutStream); ;
Response.End();
}
The file is download to "Download" folder.
Well there are two things
first of all what you want to achieve can't be done by downoad option it means we can read file and write in system memory as per our desired location but in that case No download popup will see so you have to decide if you need download popup and no desired location or vice versa.
Related
I've created an endpoint that generates an Excel file. It's supposed to function as a GET in case I want some other code to POST it to a different endpoint for emailing, or in case I want to just download the Excel file by hitting the endpoint manually in a browser. It's downloading the Excel file, but when I try to open it I see the message "Excel cannot open the file 'blahblah' because the file format or file extension is not valid. Verify that the file has not been corrupted and that the file extension matches the format of the file."
After getting that error, I've tried changing the MIME type in my response content field and/or file extension, and the error goes away and the file opens with the following warning: "The file format and extension of "blah blah" don't match. The file could be corrupted or unsafe. Unless you trust its source, don't open it. Do you want to open it anyway?" If I open it anyway, the file is still empty.
Here is the code where I take the ExcelPackage I created and add it to the response.
var response = HttpContext.Current.Response;
response.ContentType = "application/vnd.openxmlformats- officedocument.spreadsheetml.sheet";
var fileName = string.Format("blahblah-{0}.xls", InstantPattern.CreateWithInvariantCulture("yyyy-dd-M-HH-mm-ss").Format(_clock.Now));
response.AddHeader("content-disposition", string.Format("attachment; filename={0}", fileName));
response.BinaryWrite(excelPackage.GetAsByteArray());
I've tried adding in a different mime type like application/excel. I've tried using the .xlsx file extension instead of xls. Nothing has really worked. I know that the ExcelPackage workbook's worksheets actually have the data I want, though, because when I debug and hover over the objects I see the cell values that I'm expecting to make it into the file. So what am I doing wrong?
I've tried generating the excelPackage in two ways, both while inside a using block. Like this:
using (var excelPackage = new ExcelPackage())
{
// generate and download excel file
}
And also like this:
using (var excelPackage = new ExcelPackage(new FileInfo(fileName)))
{
// generate and download excel file
}
I use this to send the Excel file to the browser.
HttpResponse Response = HttpContext.Current.Response;
//first convert to byte array
byte[] bin = excelPackage.GetAsByteArray();
//clear the buffer stream
Response.ClearHeaders();
Response.Clear();
Response.Buffer = true;
//add the content type
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
//set the content length, without it, length is set to -1 and could give errors
Response.AddHeader("content-length", bin.Length.ToString());
//add a filename
Response.AddHeader("content-disposition", "attachment; filename=\"" + fileName + ".xlsx\"");
//send the file to the browser
Response.OutputStream.Write(bin, 0, bin.Length);
//cleanup
Response.Flush();
HttpContext.Current.ApplicationInstance.CompleteRequest();
I have the following code to create a downloadable zip archive that works fine:
ZipFile zip = new ZipFile();
zip.AlternateEncoding = Encoding.UTF8;
zip.AlternateEncodingUsage = ZipOption.Always;
zip.AddFiles(filePaths, false, ".");
string zipName = String.Format("Files_{0}.zip", DateTime.Now.ToString("yyyy-MMM-dd"));
Response.Clear();
Response.BufferOutput = false;
Response.ContentType = "application/zip";
Response.AddHeader("content-disposition", "attachment; filename=" + zipName);
zip.Save(Response.OutputStream);
Response.End();
users usually open files within a zip archive without extracting that. unfortunately I cannot open a file without extracting when using above code to create a zip archive. when trying to open a file an extra window appears shown as below:
I tried both two namespaces: Ionic.Zip and SharpCompress and the problem appears in either one.
any help would be appreciated. tks
Your code is correct but keep in mind that XLSX file format is a zip file.
What happened, is that WinRAR treats it as an archive and just unpacks it.
You can configure WinRAR and tell it to open xlxs files using Excel.
Go to
Options -> Settings -> Viewer and select Excel as an Associated Program for *.xlsx
http://acritum.com/software/manuals/winrar/html/helpviewersettings.htm
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';
When I use the following code to download a ZIP file it appears to work. However, when I attempt to open the downloaded ZIP, I get an 'invalid compressed folder' message. When I open the ZIP in notepad I see it is filled with HTML.
string fp = Server.MapPath("directory\\file.zip");
FileInfo file = new FileInfo(fp);
if (file.Exists)
{
Response.ClearContent();
Response.AddHeader("content-disposition","attachment; filename=" + file.Name);
Response.AddHeader("content-length", file.Length.ToString());
Response.ContentType = "application/zip";
Response.TransmitFile(file.FullName);
Response.End();
}
An issue I can't seem to fix that is probably related is when I try to manually type in the address of the file (http://website.com/downloads/file.zip), I get a redirect (http://website.com/login.aspx) even when logged in as the admin. Any pointers in where to look would be greatly appreciated.
Instead of just using Response.ClearContent() also use Response.ClearHeaders() to remove all the current headers as well as the body of the response.
From MSDN, HttpResponse.ClearContent Method:
The ClearContent method does not clear header information.
I have to give one option in my website to upload multiple files and then allowing users to download those files.
I have done uploading multiple files part, however I am not much clear how I will do downloading part.
I first thought to add hyperlinks dynamically to a label for each file (as I am not sure how many files user will upload).
But then it opens file in browser and does not give option to save or open file.
Main issue is user can submit any type of file like ms doc or xls or text files etc Hence content type is not fixed.
I am not clear on how exactly I will do it I mean adding link buttons dynamically or adding hyperlinks dynamically. And after that how will I download file? I am not able to do
Response.WriteFile(Server.MapPath(#"~/logo_large.gif"));
as content type is not clear.
Please help me regarding code for download all types of files
for download the file:
public void DownLoad(string FName)
{
string path = FName;
System.IO.FileInfo file = new System.IO.FileInfo(path);
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();
}
else
{
Response.Write("This file does not exist.");
}
}
but this is for word doc/docx files. in the line: Response.ContentType = "application/octet-stream"; you have to define the type of the file.
for displaying hyperlink dynamically write a loop and go over all the files which were uploaded by the user and writh the following code:
yourdivId += "<a href='" + file.FullName + "' >" + file.Name + "</a></br>";
Hope this will help u.()
Response.Clear();
Response.ContentType = YourFile.ToString();
Response.AddHeader("Content-Disposition", "attachment;filename=" + YourFileName);
Response.OutputStream.Write(YourFile, 0, YourFile.Length);
Response.Flush();
Response.End();
I have tried this to download img,txtfile,zip file,doc it works fine..
but little problem user will face that in my case when i opened a word(doc) file its ask
me to openwith..? when i select MsWord it opened it correctly.
For showing these file you can make a grid view to show all file with a download link...
Actually you can follow different ways.
Guide the user during upload and make him specify the file type before starting upload. So the user has to select the content type from a selection. You need to save the correlation between the file and its content type.
Create a map between file extensions and mime-types (See here for example). You need to obtain the file extension and save the correlation between that file and its content type.
Try to identify the content type automatically. There is a Windows
API that let you identify the Mime Type of a file. And here is some code.
After that, you can use st mnmn solution.
You can do it like this:
try
{
string strURL=txtFileName.Text;
WebClient req=new WebClient();
HttpResponse response = HttpContext.Current.Response;
response.Clear();
response.ClearContent();
response.ClearHeaders();
response.Buffer= true;
response.AddHeader("Content-Disposition","attachment;filename=\"" + Server.MapPath(strURL) + "\"");
byte[] data=req.DownloadData(Server.MapPath(strURL));
response.BinaryWrite(data);
response.End();
}
catch(Exception ex)
{
}
You'll have to set few response headers before server sends the file to client. See How to Download a file with a hyperlink