I am using webmethod to download a .zip file but file is not download. my code run well without error, code is below:
[WebMethod]
public static void DownloadExtension(string ExtensionPath)
{
string filepath = HttpContext.Current.Server.MapPath(ExtensionPath);
FileInfo file = new FileInfo(filepath);
if (file.Exists)
{
HttpContext.Current.Response.ClearContent();
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
HttpContext.Current.Response.AddHeader("Content-Length", file.Length.ToString());
HttpContext.Current.Response.ContentType = ReturnExtension(file.Extension.ToLower());
HttpContext.Current.Response.TransmitFile(file.FullName);
HttpContext.Current.Response.End();
}
}
private static string ReturnExtension(string fileExtension)
{
switch (fileExtension)
{
case ".zip":
return "application/zip";
default:
return "application/octet-stream";
}
}
i am using VS2008 any solution thank you.
u can try this method..it worked fine for me...hope it helps you to..
protected void Page_Load(object sender, EventArgs e)
{
StartZip(Server.MapPath("directory name"), "filename");
}
protected void StartZip(string strPath, string strFileName)
{
MemoryStream ms = null;
Response.ContentType = "application/octet-stream";
strFileName = HttpUtility.UrlEncode(strFileName).Replace('+', ' ');
Response.AddHeader("Content-Disposition", "attachment; filename=" + strFileName + ".zip");
ms = new MemoryStream();
zos = new ZipOutputStream(ms);
strBaseDir = strPath + "\\";
addZipEntry(strBaseDir);
zos.Finish();
zos.Close();
Response.Clear();
Response.BinaryWrite(ms.ToArray());
Response.End();
}
protected void addZipEntry(string PathStr)
{
DirectoryInfo di = new DirectoryInfo(PathStr);
foreach (DirectoryInfo item in di.GetDirectories())
{
addZipEntry(item.FullName);
}
foreach (FileInfo item in di.GetFiles())
{
FileStream fs = File.OpenRead(item.FullName);
byte[] buffer = new byte[fs.Length];
fs.Read(buffer, 0, buffer.Length);
string strEntryName = item.FullName.Replace(strBaseDir, "");
ZipEntry entry = new ZipEntry(strEntryName);
zos.PutNextEntry(entry);
zos.Write(buffer, 0, buffer.Length);
fs.Close();
}
}
Try to download the file through a .ashx handler file.
Related
In my method in controller I use the following code to save pdf.
HtmlDocument doc = new HtmlDocument();
doc.LoadHtml(htmlContent);
HtmlNode node = doc.GetElementbyId("DetailsToPDF");
HtmlToPdfConverter htmlToPdf = new HtmlToPdfConverter();
var pdfBytes = htmlToPdf.GeneratePdf("<html><body>" + node.InnerHtml + "</body></html>");
Response.ContentType = "application/pdf";
Response.ContentEncoding = System.Text.Encoding.UTF8;
Response.AddHeader("Content-Disposition", "attachment; filename=TEST.pdf");
Response.BinaryWrite(pdfBytes);
Response.Flush();
Response.End();
Everything has passed without any exceptions in debugger. However file is not saved. What am I doing wrong?
The recommended way to return a File in ASP.NET MVC is using the File() helper method:
public ActionResult Download()
{
// Starting with pdfBytes here...
// ...
var pdfBytes = htmlToPdf.GeneratePdf("<html><body>" + node.InnerHtml + "</body></html>");
var contentDisposition = new System.Net.Mime.ContentDisposition
{
FileName = "TEST.pdf",
Inline = false
};
Response.AppendHeader("Content-Disposition", contentDisposition.ToString());
return File(pdfBytes, "application/pdf");
}
string path = Server.MapPath("~/Content/files/newPDFFile.pdf");
WebClient client = new WebClient();
Byte[] buffer = client.DownloadData(path);
if (buffer != null)
{
Response.Clear();
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;filename=" + "PDFfile.pdf");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.BinaryWrite(buffer);
Response.End();
}
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();
<%# WebHandler Language="C#" Class="dlde" %>
using System;
using System.Web;
public class dlde : IHttpHandler {
public void ProcessRequest (HttpContext context) {
var fileName = #"D:\Error.txt";
var r = context.Response;
r.AddHeader("Content-Disposition", "attachment; filename=" + fileName);
r.ContentType = "text/plain";
r.WriteFile(context.Server.MapPath(fileName));
}
public bool IsReusable {
get {
return false;
}
}
}
I want to download the .txt file from the server system from the specified directory...i tried with this code,but i am getting error,invalid virtual path..How to get the file ,from the server system ..please help me...
try this by using "WebClient "
string remoteUri = "http://Yoursite.com/file.txt";
string fileName = #"D:\";
WebClient myWebClient = new WebClient();
myWebClient.DownloadFile(remoteUri, fileName);
Learning from MSDN for namespace
string fName = #"D:\Error.txt";
System.IO.FileStream fs = System.IO.File.Open(fName, System.IO.FileMode.Open);
byte[] btFile = new byte[fs.Length];
fs.Read(btFile, 0, Convert.ToInt32(fs.Length));
fs.Close();
context.Response.Clear();
context.Response.ClearHeaders();
context.Response.AddHeader("Content-disposition", "attachment;
filename=" + HttpUtility.UrlEncode(fname, System.Text.Encoding.UTF8));
context.Response.ContentType = "text/plain";
context.Response.BinaryWrite(btFile);
string fName = #hdfRuta.Value; //Ruta donde se encuentra el archivo txt Ejm: c:\log\log21082018.txt
System.IO.FileStream fs = System.IO.File.Open(fName,
System.IO.FileMode.Open);
byte[] btFile = new byte[fs.Length];
fs.Read(btFile, 0, Convert.ToInt32(fs.Length));
fs.Close();
Response.Clear();
Response.ClearHeaders();
Response.AddHeader("Content-Disposition", "attachment; filename=" + hdfNombreArchivo.Value); //hdfNombreArchivo: Nombre del archivo .txt a generarse Ejm: Log_21_08_2018.txt
EnableViewState = false;
Response.ContentType = "text/plain";
Response.BinaryWrite(btFile);
Response.End();
protected void btnBajarLog_PreRender(object sender, EventArgs e)
{
Button btn = (Button)sender;
ScriptManager newScriptManager =
(ScriptManager)Page.FindControl("scmRegistroMasivoEvento");
newScriptManager.RegisterPostBackControl(btn);
}
I use TransmitFile and WriteFile to write an Excel File, but anyone does not work correctly
my code is :
// Get the Physical Path of the file(test.doc)
string filepath = newFilePath;
// Create New instance of FileInfo class to get the properties of the file being downloaded
FileInfo file = new FileInfo(filepath);
// Checking if file exists
if (file.Exists)
{
// Clear the content of the response
HttpContext.Current.Response.ClearContent();
// LINE1: Add the file name and attachment, which will force the open/cance/save dialog to show, to the header
HttpContext.Current.Response.AddHeader("Content-Disposition", String.Format("attachment; filename={0}", file.Name));
// Add the file size into the response header
HttpContext.Current.Response.AddHeader("Content-Length", file.Length.ToString());
// Set the ContentType
HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
// Write the file into the response (TransmitFile is for ASP.NET 2.0. In ASP.NET 1.1 you have to use WriteFile instead)
HttpContext.Current.Response.TransmitFile(file.FullName);
}
FileStream sourceFile = new FileStream(file.FullName, FileMode.Open);
float FileSize;
FileSize = sourceFile.Length;
byte[] getContent = new byte[(int)FileSize];
sourceFile.Read(getContent, 0, (int)sourceFile.Length);
sourceFile.Close();
HttpContext.Current.Response.ClearContent();
HttpContext.Current.Response.ClearHeaders();
HttpContext.Current.Response.Buffer = true;
HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
HttpContext.Current.Response.AddHeader("Content-Length", getContent.Length.ToString());
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName);
HttpContext.Current.Response.BinaryWrite(getContent);
I would simplify it to this instead:
public ActionResult ExcelDoc(string newFilePath)
{
string filepath = newFilePath;
// Create New instance of FileInfo class to get the properties of the file being downloaded
FileInfo file = new FileInfo(filepath);
// Checking if file exists
if (file.Exists)
{
var fileBytes = System.IO.File.ReadAllBytes(filepath);
Response.AddHeader("Content-Disposition", String.Format("attachment; filename={0}", file.Name));
return File(new MemoryStream(fileBytes), "application/vnd.ms-excel");
}
else
{
return Content("File does not exist");
}
}
I got a response which contains a PDF file
HttpWebResponse res = (HttpWebResponse)HttpWRequest.GetResponse();
Stream pdf = res.GetResponseStream();
I want to show this PDF on web browser without save it in a file. How could I do that?
I'm using the following code and works fine.
public static void SendDataByteFileToClient(HttpContext context, byte[] data, string fileName, string contentType, bool clearHeaders = true)
{
if (clearHeaders)
{
context.Response.Clear();
context.Response.ClearHeaders();
}
context.Response.BufferOutput = true;
context.Response.ContentType = contentType;
context.Response.AddHeader("Content-Disposition", "inline; filename=" + fileName);
context.Response.AddHeader("Content-Length", data.Length.ToString());
if (BrowserHelper.IsOfType(BrowserTypeEnum.IE) && BrowserHelper.Version < 9)
{
context.Response.Cache.SetCacheability(HttpCacheability.Private);
context.Response.Cache.SetMaxAge(TimeSpan.FromMilliseconds(1));
}
else
{
context.Response.Cache.SetCacheability(HttpCacheability.NoCache);//IE set to not cache
context.Response.Cache.SetNoStore();//Firefox/Chrome not to cache
context.Response.Cache.SetExpires(DateTime.UtcNow); //for safe measure expire it immediately
}
if (data.Length > 0)
{
context.Response.BinaryWrite(data);
}
context.Response.End();
}
HttpWebResponse res = (HttpWebResponse)HttpWRequest.GetResponse();
Stream pdfdata = res.GetResponseStream();
string path = pdfdata.ToString();
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);
Response.End();
}