I am having some problems with downloading files with the save dialog.
My code executes with no errors but no save dialog shows up. Not in FF, not in chrome and not in IE. The attachment can have the following extensions: .jpg,.jpeg,.png,.bmp,.pdf,.txt,.docx. That's why I use Response.ContentType = "application/octet-stream"; (see in code below).
protected void btnDownload_OnCommand(object sender, CommandEventArgs e)
{
//Get the attachment to download from the webservice
RCX.AddressAttachment attachment = ShopClient.GetAddressAttachment(ServiceContext,
new AddressAttachmentCriteria()
{
Id = (string) e.CommandArgument //= AttachmentID
});
//Get a random filename
var fileName = string.Format("{0}{1}", Guid.NewGuid(), attachment.FileExtension);
//Get the physicalPath to save the file
var physicalPath = string.Format(#"{0}\Attachments\{1}", System.AppDomain.CurrentDomain.BaseDirectory,
fileName);
//Get the webpath to navigate to the file
var webPath = string.Format("{0}Attachments/{1}", Misc.BaseUrl(Request.Url), fileName);
//Create file if not exists
using (new FileStream(physicalPath, FileMode.OpenOrCreate))
{
}
//Write bytes to file
System.IO.File.WriteAllBytes(physicalPath, attachment.Attachment);
var fileInfo = new FileInfo(physicalPath);
//Try to open the save dialog, what is wrong here?
Response.Clear();
Response.ContentType = "application/octet-stream";
Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0};", fileName));
Response.AddHeader("Content-Length", fileInfo.Length.ToString());
Response.WriteFile(physicalPath);
Response.End();
}
The file exists after executing the WriteAllBytes(string path, byte[] bytearray) method.
If I navigate to the webPath in my code, I can also see the file in the browser (see code below).
Response.Redirect(webPath);
What could I be doing wrong?
Many thanks.
Try this
Response.Flush();
before the Response.End();
Related
I'm debugging a rather odd situation involving DotNetZip and ASP.NET. Long story short, the resulting zip files that are being created by the code are being reliably downloaded by Firefox, but most other browsers are intermittently returning a Network Error. I've examined the code and it reads about as generically as anything that involves DotNetZip.
Any clues?
Thanks!
EDIT: Here's the complete method. As I mentioned, it's about as generic as it gets:
protected void btnDownloadFolders_Click(object sender, EventArgs e)
{
//Current File path
var diRoot = new DirectoryInfo(_currentDirectoryPath);
var allFiles = Directory.GetFiles(diRoot.FullName, "*.*", SearchOption.AllDirectories);
Response.Clear();
Response.BufferOutput = false;
var archiveName = String.Format("{0}-{1}.zip", diRoot.Name, DateTime.Now.ToString("yyyy-MM-dd HHmmss"));
Response.ContentType = "application/zip";
Response.AddHeader("content-disposition", "inline; filename=\"" + archiveName + "\"");
using (var zip = new ZipFile())
{
foreach (var strFile in allFiles)
{
var strFileName = Path.GetFileName(strFile);
zip.AddFile(strFile,
strFile.Replace("\\" + strFileName, string.Empty).Replace(diRoot.FullName, string.Empty));
}
zip.Save(Response.OutputStream);
}
Response.Close();
}
It could be because you are not sending the content-length. I've seen errors occur in sending files to the browser where it was not specified. So create the zip file in a MemoryStream. save the stream to a Byte Array so you can send the length as a Response also. Although I can't say for sure that it will fix your specific problem.
byte[] bin;
using (MemoryStream ms = new MemoryStream())
{
using (var zip = new ZipFile())
{
foreach (var strFile in allFiles)
{
var strFileName = Path.GetFileName(strFile);
zip.AddFile(strFile, strFile.Replace("\\" + strFileName, string.Empty).Replace(diRoot.FullName, string.Empty));
}
//save the zip into the memorystream
zip.Save(ms);
}
//save the stream into the byte array
bin = ms.ToArray();
}
//clear the buffer stream
Response.ClearHeaders();
Response.Clear();
Response.Buffer = true;
//set the correct contenttype
Response.ContentType = "application/zip";
//set the filename for the zip file package
Response.AddHeader("content-disposition", "attachment; filename=\"" + archiveName + "\"");
//set the correct length of the data being send
Response.AddHeader("content-length", bin.Length.ToString());
//send the byte array to the browser
Response.OutputStream.Write(bin, 0, bin.Length);
//cleanup
Response.Flush();
HttpContext.Current.ApplicationInstance.CompleteRequest();
I've been searching around the internet, but couldn't find any useful answer.
I have an ASP.NET web site, which is deployed on server.
The ASP.NET web site on the server can access a directory called W:/ .
The clients in the company can access the web site. The web site lists in a ListBox all the PDF files from the W:/ directory. The client should be able to select PDF files from the listbox and save them to it's local PC by selecting a location for it.
Something like save as file on web pages.
Could you provide me some solution or work around ?
Finally I've found an article, which Prompts a Save Dialog Box to Download a File from ASP.NET
I post it here, might help somebody else as well and save some time.
String FileName = "FileName.txt";
String FilePath = "C:/...."; //Replace this
System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
response.ClearContent();
response.Clear();
response.ContentType = "text/plain";
response.AddHeader("Content-Disposition", "attachment; filename=" + FileName + ";");
response.TransmitFile(FilePath);
response.Flush();
response.End();
This is an extension to user1734609's solution that gets a file locally.
To download a file from the server to client:
public void DownloadFile()
{
String FileName = "201604112318571964-sample2.txt";
String FilePath = AppDomain.CurrentDomain.BaseDirectory + "/App_Data/Uploads/" + FileName;
System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
response.ClearContent();
response.Clear();
response.ContentType = "text/plain";
response.AddHeader("Content-Disposition", "attachment; filename=" + FileName + ";");
response.TransmitFile(FilePath);
response.Flush();
response.End();
}
The correct keywords are "File Browser asp.net" to find a lot of examples with source code.
Here is one from codeproject:
http://www.codeproject.com/Articles/301328/ASP-NETUser-Control-File-Browser
Get file contents in byte[] from W drive and write it to local file.
byte[] data = File.ReadAllBytes(WDriveFilePath)
FileStream file = File.Create(HttpContext.Current.Server.MapPath(MyLocalFile));
file.Write(data, 0, data.Length);
file.Close();
I have done something like this to get the file .
protected void btnExportFile_Click(object sender, EventArgs e)
{
try
{
Thread newThread = new Thread(new ThreadStart(ThreadMethod));
newThread.SetApartmentState(ApartmentState.STA);
newThread.Start();
// try using threads as you will get a Current thread must be set to single thread apartment (STA) mode before OLE Exception .
}
catch (Exception ex)
{
}
}
static void ThreadMethod()
{
Stream myStream;
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.FilterIndex = 2;
saveFileDialog1.RestoreDirectory = true;
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
if ((myStream = saveFileDialog1.OpenFile()) != null)
{
// Code to write the stream goes here.
myStream.Close();
}
}
}
I've been searching around the internet, but couldn't find any useful answer.
I have an ASP.NET web site, which is deployed on server.
The ASP.NET web site on the server can access a directory called W:/ .
The clients in the company can access the web site. The web site lists in a ListBox all the PDF files from the W:/ directory. The client should be able to select PDF files from the listbox and save them to it's local PC by selecting a location for it.
Something like save as file on web pages.
Could you provide me some solution or work around ?
Finally I've found an article, which Prompts a Save Dialog Box to Download a File from ASP.NET
I post it here, might help somebody else as well and save some time.
String FileName = "FileName.txt";
String FilePath = "C:/...."; //Replace this
System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
response.ClearContent();
response.Clear();
response.ContentType = "text/plain";
response.AddHeader("Content-Disposition", "attachment; filename=" + FileName + ";");
response.TransmitFile(FilePath);
response.Flush();
response.End();
This is an extension to user1734609's solution that gets a file locally.
To download a file from the server to client:
public void DownloadFile()
{
String FileName = "201604112318571964-sample2.txt";
String FilePath = AppDomain.CurrentDomain.BaseDirectory + "/App_Data/Uploads/" + FileName;
System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
response.ClearContent();
response.Clear();
response.ContentType = "text/plain";
response.AddHeader("Content-Disposition", "attachment; filename=" + FileName + ";");
response.TransmitFile(FilePath);
response.Flush();
response.End();
}
The correct keywords are "File Browser asp.net" to find a lot of examples with source code.
Here is one from codeproject:
http://www.codeproject.com/Articles/301328/ASP-NETUser-Control-File-Browser
Get file contents in byte[] from W drive and write it to local file.
byte[] data = File.ReadAllBytes(WDriveFilePath)
FileStream file = File.Create(HttpContext.Current.Server.MapPath(MyLocalFile));
file.Write(data, 0, data.Length);
file.Close();
I have done something like this to get the file .
protected void btnExportFile_Click(object sender, EventArgs e)
{
try
{
Thread newThread = new Thread(new ThreadStart(ThreadMethod));
newThread.SetApartmentState(ApartmentState.STA);
newThread.Start();
// try using threads as you will get a Current thread must be set to single thread apartment (STA) mode before OLE Exception .
}
catch (Exception ex)
{
}
}
static void ThreadMethod()
{
Stream myStream;
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.FilterIndex = 2;
saveFileDialog1.RestoreDirectory = true;
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
if ((myStream = saveFileDialog1.OpenFile()) != null)
{
// Code to write the stream goes here.
myStream.Close();
}
}
}
In my application I'm uploading a file which has Swedish characters in file name. It works fine.
But when I try to download it, I get an error: "An invalid character was found in the mail header" ..Could you help regarding this
Please see my code
public ActionResult Download(Guid id)
{
var attachment = AttachmentService.GetAttachmentById(id);
var cd = new ContentDisposition
{
FileName = Utility.GetCleanedFileName(((FileAttachment)attachment).FileName),
Inline = false,
};
var file = File("\\App_Data" +((FileAttachment)attachment).FilePath, "Application");
Response.ClearHeaders();
Response.Clear();
Response.ContentType = file.ContentType;
Response.AppendHeader("Content-Disposition", cd.ToString());
var filePath = "\\App_Data" + ((FileAttachment) attachment).FilePath;
Response.WriteFile(filePath);
Response.End();
return file;
}
Please try to encode the filename using HttpUtility.UrlPathEncode.
http://msdn.microsoft.com/en-us/library/system.web.httputility.urlpathencode.aspx
How can I open any file, specified by a path, in ASP.NET programatically?
I tried the snippet below but it reads the contents of the file instead of opening the file:
string fileName = #"C:\deneme.txt";
StreamReader sr = File.OpenText(fileName);
while (sr.Peek() != -1)
{
Response.Write(sr.ReadLine() + "<br>");
}
sr.Close();
I also tried the File.Open method.
You can Response.Redirect to file if you're just opeining it
or if file is being downloaded you can use the folling code;
public void DownloadFile(string fileName)
{
Response.Clear();
Response.ContentType = #"application\octet-stream";
System.IO.FileInfo file = new System.IO.FileInfo(Server.MapPath(FileName));
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.Flush();
}
If you want the file to be opened on the client side,Create an HTTP Handler and set the appropriate mime type on your response before streaming it out from your handler.
for more information I ask question near to your one before.
how to open file with its application