Hi all wondering if someone can help; i've written this code which will generate an excel spreadsheet and save it to a specified location. I want to then display a "Save as" dialogue box by reading the file from the stored location and then asking then user where they want to store it. The excel file is being generated fine and i can open it normally! However my problem is the code i've written seems to be outputting the file directly to my browser, so i get all the contents of the excel file on my browser screen, not displaying the save as dialogue box as expected!
public ActionResult FormSuccess()
{
String FileName = System.Configuration.ConfigurationManager.AppSettings["FileName"].ToString();
String FilePath = System.Configuration.ConfigurationManager.AppSettings["FileSaveLocation"].ToString();
System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
response.ClearContent();
response.Clear();
response.ContentType = "application/vnd.xls";
response.AddHeader("Content-Disposition", "attachment; filename=" + FileName + ";");
response.TransmitFile(FilePath + FileName);
response.End();
return PartialView("FormSuccess");
}
Yo Vince, how's tricks? Still wearing the medallion? :)
Shouldn't you be using FileContentResult instead of PartialView? You won't be able to return the file AND the HTML "success" content in the same call - you should probably call the PartialView first, which would then use javascript to open the FileContentResult URL in a new window.
See this: http://www.mikesdotnetting.com/Article/125/ASP.NET-MVC-Uploading-and-Downloading-Files
and this url as well :
http://weblogs.asp.net/rajbk/archive/2010/05/03/actionresult-types-in-mvc2.aspx
I think that your problem is that you return PartialView. Let me give you small exmaple of my implemetation:
public ActionResult FileXls()
{
var output = new MemoryStream();
var writer = new StreamWriter(output);
//create your workbook excel file
....
//workbook.Save(output);
writer.Flush();
output.Position = 0;
return File(output, "text/excel", "file.xls");
}
Related
This question was migrated from Super User because it can be answered on Stack Overflow.
Migrated 14 days ago.
This is a C# code for a Web Form page named "upload.aspx" which allows the user to upload a PDF file and store it in the server. The file uploaded must be a PDF file, and all the text boxes must be filled before submission. The file name is saved in the database as a string with the format of "GUID.pdf", Guid.NewGuid().ToString().
tTR.FileName = Guid.NewGuid().ToString() + ".pdf";
dataBaseDataContext.TTRs.InsertOnSubmit(tTR);
dataBaseDataContext.SubmitChanges();
String path = Server.MapPath("Attachments/" + tTR.FileName);
FileUploadtoServer.SaveAs(path);
Response.Write("<script>alert('Successfully Inserted!')</script>");
Invoice.Text = "";
Manufacture.Text = "";
HeatCode.Text = "";
Description.Text = "";
PO_Number.Text = "";
i created a search function that allows the user to search for based on Heat Code, Item Code, PO Number, and Description. he user can also edit and download the file by clicking on the "Edit / Download" link. The problem here is in my Download button. It's not downloading/ able to read the path. i can see the pdf exist in the Attachment folder but it's not able to find the correct file name associated to the heat code.
private void BindData(List<TTR> Data)
{
try
{
if (Data.Count > 0)
{
StringBuilder append = new StringBuilder();
foreach (TTR tTR in Data)
{
string PdfGuid = tTR.FileName;
append.Append("
}
tdList.InnerHtml = append.ToString();
}
}
catch (Exception)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
try
{
string filePath = Server.MapPath("~/Attachments/" + filename + ".pdf");
byte[] content = File.ReadAllBytes(filePath);
Response.Clear();
Response.ContentType = "application/pdf";
Response.AddHeader("Content-Disposition", "attachment; filename=" + filename + ".pdf");
Response.Buffer = true;
Response.BinaryWrite(content);
Response.End();
}
catch (Exception)
{
This is a C# code for a web form page named "upload.aspx" that allows a user to upload a PDF file, store it on the server, and save its file name in the database as a string with the format "GUID.pdf", where GUID is a unique identifier generated using Guid.NewGuid().ToString(). Before submission, all the text boxes must be filled, and the uploaded file must be a PDF.
The code also includes a search function that allows the user to search for files based on Heat Code, Item Code, PO Number, and Description. The user can also edit and download the file by clicking on the "Edit / Download" link. However, the download button is encountering issues as it is not able to find the correct file name associated with the heat code and download the file.
The problem seems to be with the code that retrieves the file path, reads the contents of the file, sets the content type as "application/pdf", and writes the contents to the response stream. The code is trying to read the file from the server's "Attachments" folder using the file path, but it seems to be encountering issues finding the correct file.
I want to make the browser download a PDF document from server instead of opening the file in browser itself. I am using C#.
Below is my sample code which I used. It not working..
string filename = "Sample server url";
response.redirect(filename);
You should look at the "Content-Disposition" header; for example setting "Content-Disposition" to "attachment; filename=foo.pdf" will prompt the user (typically) with a "Save as: foo.pdf" dialog, rather than opening it. This, however, needs to come from the request that is doing the download, so you can't do this during a redirect. However, ASP.NET offers Response.TransmitFile for this purpose. For example (assuming you aren't using MVC, which has other preferred options):
Response.Clear();
Response.ContentType = "application/pdf";
Response.AppendHeader("Content-Disposition", "attachment; filename=foo.pdf");
Response.TransmitFile(filePath);
Response.End();
If you want to render the file(s) so that you could save them at your end instead of opening in the browser, you may try the following code snippet:
//create new MemoryStream object and add PDF file’s content to outStream.
MemoryStream outStream = new MemoryStream();
//specify the duration of time before a page cached on a browser expires
Response.Expires = 0;
//specify the property to buffer the output page
Response.Buffer = true;
//erase any buffered HTML output
Response.ClearContent();
//add a new HTML header and value to the Response sent to the client
Response.AddHeader(“content-disposition”, “inline; filename=” + “output.pdf”);
//specify the HTTP content type for Response as Pdf
Response.ContentType = “application/pdf”;
//write specified information of current HTTP output to Byte array
Response.BinaryWrite(outStream.ToArray());
//close the output stream
outStream.Close();
//end the processing of the current page to ensure that no other HTML content is sent
Response.End();
However, if you want to download the file using a client application then you'll have to use the WebClient class.
I use this by setting inline parameter to true it will show in browser false it will show save as dialog in browser.
public void ExportReport(XtraReport report, string fileName, string fileType, bool inline)
{
MemoryStream stream = new MemoryStream();
Response.Clear();
if (fileType == "xls")
report.ExportToXls(stream);
if (fileType == "pdf")
report.ExportToPdf(stream);
if (fileType == "rtf")
report.ExportToRtf(stream);
if (fileType == "csv")
report.ExportToCsv(stream);
Response.ContentType = "application/" + fileType;
Response.AddHeader("Accept-Header", stream.Length.ToString());
Response.AddHeader("Content-Disposition", String.Format("{0}; filename={1}.{2}", (inline ? "Inline" : "Attachment"), fileName, fileType));
Response.AddHeader("Content-Length", stream.Length.ToString());
//Response.ContentEncoding = System.Text.Encoding.Default;
Response.BinaryWrite(stream.ToArray());
Response.End();
}
In case if we are trying to write a bytes array then we can use below one.
Response.Clear();
Response.ContentType = "application/pdf";
Response.AppendHeader("Content-Disposition", "attachment; filename=file.pdf");
Response.BufferOutput = true;
Response.AddHeader("Content-Length", docBytes.Length.ToString());
Response.BinaryWrite(docBytes);
Response.End();
They are almost same in most of the cases but there is a difference:
Add Header will replace the previous entry with the same key
Append header will not replace the key, rather will add another one.
I am generating dynamic .pdf file using asp.net, on some browsers e.g firefox displays the pdf as expected but on I.E & Safari its giving a "Save As" rather than displaying it in the browser. I have used an iFrame for the same. Also to display pdf file is it mandate that the client should have adobe reader or some plugin to display the pdf?
protected void bttnpdf_Click(object sender, EventArgs e)
{
string FilePath = Server.MapPath("sample.pdf");
WebClient User = new WebClient();
Byte[] FileBuffer = User.DownloadData(FilePath);
if (FileBuffer != null)
{
Response.ContentType = "application/pdf";
Response.AddHeader("content-length", FileBuffer.Length.ToString());
Response.BinaryWrite(FileBuffer);
}
}
Any help would be appreciated.
Thanks in advance
in aspx file :
<div>
<iframe id="myFrame" runat="server" style="width:600px; height:500px;" frameborder="0"></iframe>
</div>
in cs file :
myFrame.src="yourPDFPath"
for example
myFrame.Src = "http://docs.google.com/gview?url=http://path.com/to/your/pdf.pdf&embedded=true";
When I have done this I have also added a content disposition. In the code (can't share it all as it is production code) there is a function that finds a record in the database and returns a FileHandle.
The function returns a FileHandle:
FileStream stream = new FileStream(filePath, FileMode.Open);
var fileHandle = new FileHandle
{
FileStream = stream,
ContentType = "application/pdf",
Filename = fileDownloadName
};
where filePath is the path to the file (e.g. Server.MapPath("sample.pdf") ). In the controller action I have:
var cd = new System.Net.Mime.ContentDisposition
{
// for example foo.bak
FileName = fileHandle.Filename,
// always prompt the user for downloading, set to true if you want
// the browser to try to show the file inline
Inline = true,
};
Response.AppendHeader("Content-Disposition", cd.ToString());
return File(fileHandle.FileStream, fileHandle.ContentType);
Add below line before the line Response.BinaryWrite(FileBuffer);.
Response.AddHeader("Content-Disposition", "inline");
add this header to reponse , so that PDF files will opened in browser itself.
I have designed a website through which when i click a button a .EXE file should download from specific path from my computer.
But its not downloading the exe file instead its downloading the aspx page of the website.
I use the following code:
WebClient myWebClient = new WebClient();
// Concatenate the domain with the Web resource filename.
myWebClient.DownloadFile("http://localhost:1181/Compile/compilers/sample2.exe", "sample2.exe");
Can you please try this.
string filename = "yourfilename";
if (filename != "")
{
string path = Server.MapPath(filename);
System.IO.FileInfo file = new System.IO.FileInfo(path);
if (file.Exists)
{
Response.Clear();
//Content-Disposition will tell the browser how to treat the file.(e.g. in case of jpg file, Either to display the file in browser or download it)
//Here the attachement is important. which is telling the browser to output as an attachment and the name that is to be displayed on the download dialog
Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
//Telling length of the content..
Response.AddHeader("Content-Length", file.Length.ToString());
//Type of the file, whether it is exe, pdf, jpeg etc etc
Response.ContentType = "application/octet-stream";
//Writing the content of the file in response to send back to client..
Response.WriteFile(file.FullName);
Response.End();
}
else
{
Response.Write("This file does not exist.");
}
}
I hope my edited comment will help to understand. But note: It is just a rough summary. You can do a lot more than this.
I'm getting a file from a database in byte [] format and want user to see download dialog before Linq will take it from the database. It's in C# and ASP.NET.
Now, it's like this:
User choose a file, click on it.
In code I get id of file clicked and using Linq I'm downloading.
Then I send the file by Response.OutputStream.Write(content, 0,
content.Length);
Before a file is downloaded from the database user won't see any
download dialog.
What can I do if I want users to see the download dialog before file is downloaded?
Code:
Getting file by id:
public static byte[] getFile(Guid id)
{
var linqFile = from file in MyDB.Files
where file.IdPliku.Equals(id)
select new
{
Content = file.Content
};
return linqFile.ToList().FirstOrDefault().Content.ToArray();
}
Saving file:
public void SaveFile(Guid fileID, string filename, string mimeTypes)
{
try
{
byte[] content = FileService.getFile(fileID);
Response.ClearContent();
Response.ClearHeaders();
Response.ContentType = mimeTypes;
Response.AppendHeader("Accept-Ranges", "bytes");
Response.AppendHeader("Content-Range", string.Format("0-{0}/{1}", content.Length, content.Length));
Response.AppendHeader("Content-Length", content.Length.ToString());
Response.AppendHeader("Content-Encoding", "utf-8");
Response.AppendHeader("Content-Type", Response.ContentType);
Response.AppendHeader("Content-Disposition", "attachment; filename= " + HttpUtility.UrlEncode(filename));
Response.OutputStream.Write(content, 0, content.Length);
//Response.BinaryWrite(content);
Response.Flush();
}
finally
{
Response.Close();
}
}
You are my hope.
your issue is here:
byte[] content = FileService.getFile(fileID);
because in this line you allocate the whole file in the web server's RAM and put everything in there, all content of the file from the database; what happens later does not matter anymore because you have already downloaded from db to web server in this line!!!
I am having such Deja-vu because I am sure I have given exactly the same comment on a very same question few weeks ago. Can't find it now, search for something like this here in SO.
In fact the solution is to stream directly to the output stream of the Response avoiding your byte[] array allocation above, to get this your data layer should of course support it and if it does not you could add a method for this. You want to use SQL Server filestream or something similar.