I am trying to view files from a folder in asp.net. I have tried using the "Response" class and its many functions to view files but so far I have been unsuccessful. Mostly using the Response class allows me to download the files but not view them in the browser. Most of what I have seen online suggests the same thing which is to use this bit of code:
string fileName = "Myfile.pdf";
Response.ContentType = "application/pdf";
Response.AddHeader("Content-Disposition", "inline; filename="+fileName);
But again, this only allows me to download the file and not view it in the browser.
Any suggestions on how I can do this?
This is what works for me:
Response.Clear();
Response.AddHeader("Content-Length", binaryFile.Length.ToString(CultureInfo.InvariantCulture));
//Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}", title)); // save file as attachment
Response.AddHeader("Content-Disposition", string.Format("inline; filename={0}", title)); // display inline in browser
Response.AddHeader("Content-Type", "application/pdf");
Response.BinaryWrite(binaryFile);
Response.Flush();
Response.End();
Here is some nice project using free HTML based file browser:
https://github.com/magicbruno/FileBrowser
Alternative would be to use something like ASP.NET GridView and handle browsing specific folder. Here is short sample.
ASPX code:
<asp:GridView ID="GridView1" runat="server"></asp:GridView>
Page code:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
DisplayDirectoryContent(Server.MapPath("~"));
}
}
void DisplayDirectoryContent(string directory)
{
System.Data.DataTable data = new System.Data.DataTable();
data.Columns.Add("Name",typeof(string));
data.Columns.Add("IsFolder", typeof(bool));
foreach (var dir in System.IO.Directory.GetDirectories(directory))
{
System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(directory);
data.Rows.Add(new object[] { di.Name, true });
}
foreach (var file in System.IO.Directory.GetFiles(directory))
{
System.IO.FileInfo fi = new System.IO.FileInfo(file);
data.Rows.Add(new object[] { fi.Name, false });
}
GridView1.DataSource = data;
GridView1.DataBind();
}
Take notice that you cant directly view any file in browser, but you can link downolad action to GridView (similar to your code). This is how it works.
Related
This question already has answers here:
How do I export to Excel?
(3 answers)
Closed 6 years ago.
I am trying to import data from excel to mvc
public void DownloadAsExcelOrderReports()
{
try
{
var list = _reportWork.GetList();
GridView gv = new GridView();
gv.DataSource = list;
gv.DataBind();
Response.ClearContent();
Response.Buffer = true;
Response.ContentEncoding = System.Text.Encoding.UTF32;
Response.AddHeader("content-disposition", "attachment; filename=Marklist.xls");
Response.ContentType = "application/ms-excel";
Response.Charset = "";
using (StringWriter sw = new StringWriter())
{
using (HtmlTextWriter htw = new HtmlTextWriter(sw))
{
gv.RenderControl(htw);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}
}
}
catch (Exception ex)
{
}
}
This is the code I found online.I get an output like this.
Normally it has to fill in the table itself automatically into excel.I can't see, what i missed.
GridView is a WebControl. You put data into it (DataBind) and it emits html (RenderControl) which is supposed to be sent to the browser and the browser will show it as a table (tr and td tags).
In your case you're trying to show that html code within an excel document and that makes no sense.
The best I've found is to use EPPlus, which you can get from NuGet Package Manager. You have to tie together your data to what you want the excel doc to look like. It's a bit fiddly but there's no alternative.
I have tried a code to open a pdf file in a web browser. It give to allows me to open the file through pdf reader no in the browser. Almost all the codes i found over the internet are also same as this code. But this code doesn't work as i expected.
Help me to figure out the problem in here. I'm using a link button in the aspx.
Here is my code
aspx code
<asp:LinkButton ID="pdfViewLOP" runat="server" Style="margin-left: 10px" OnClick="pdfViewLOP_Click" >View PDF</asp:LinkButton>
aspx.cs
Response.Write(string.Format("<script>window.open('{0}','_blank');</script>", "viewPDF.aspx"));
Code of the new page which pdf should be displayed
string name=Session["name"].ToString();
int refNo = Convert.ToInt32(name);
string FilePath = Server.MapPath("~/filesPDF/" + refNo + ".pdf");
WebClient User = new WebClient();
Byte[] buffer = User.DownloadData(FilePath);
if (buffer != null)
{
Response.Clear();
Response.ContentType = "application/pdf";
Response.AddHeader("content-length", buffer.Length.ToString());
Response.BinaryWrite(buffer);
}
How if you directly create a hyperlink with target _blank and path of file as a href of hyperlink.
So the result hyperlink generated inside the html page is
View PDF
I have a working Excel Report code. Still, when I click the button the file goes directly to my download folder, without giving me the option to change its name or selecting where I want to save it.
Code is the following:
public void GetExcel()
{
var list = (IList<LeaseViewModel>)Session["currentList"];
var grd = new GridView { DataSource = list, AutoGenerateColumns = true };
grd.DataBind();
Response.ClearContent();
Response.AddHeader("Content-type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
Response.AddHeader("content-disposition", "attachment;filename=Leases.xls");
Response.ContentType = "application/excel";
var swr = new StringWriter();
var tw = new HtmlTextWriter(swr);
grd.RenderControl(tw);
Response.Write(swr.ToString());
Response.Flush();
Response.End();
tw.Close();
swr.Close();
}
Can somebody please indicate what should I change in order to have the window popping?
Thanks a lot.
Thanks for everybody highlighting this is a browser-configuration issue.
I thought that once I have the definition of the default name in the code I could also define it to always ask what is the name I want. I tested in different browsers though, and fact is you were right, thanks for identifying it and noticing me.
Regarding the default name issue, here is how I solve it:
Before:
Response.AddHeader("content-disposition", "attachment;filename=Leases.xls");
After:
Response.AddHeader("content-disposition", "attachment;filename=" + Session["listName"] + "_Report.xls");
Now regardless the report I export, the name is always customized.
Hope it helps other newbies like me (:
This is the code for downloading the file.
System.IO.FileStream fs = new System.IO.FileStream(Path+"\\"+fileName, System.IO.FileMode.Open, System.IO.FileAccess.Read);
byte[] ar = new byte[(int)fs.Length];
fs.Read(ar, 0, (int)fs.Length);
fs.Close();
Response.AddHeader("content-disposition", "attachment;filename=" + AccNo+".pdf");
Response.ContentType = "application/octectstream";
Response.BinaryWrite(ar);
Response.End();
When this code is executed, it will ask user to open or save the file. Instead of this I need to open a new tab or window and display the file. How can I achieve this?
NOTE:
File won't necessary be located in the website folder. It might be located in an other folder.
Response.ContentType = contentType;
HttpContext.Current.Response.AddHeader("Content-Disposition", "inline; filename=" + fileName);
Response.BinaryWrite(fileContent);
And
<asp:LinkButton OnClientClick="openInNewTab();" OnClick="CodeBehindMethod".../>
In javaScript:
<script type="text/javascript">
function openInNewTab() {
window.document.forms[0].target = '_blank';
setTimeout(function () { window.document.forms[0].target = ''; }, 0);
}
</script>
Take care to reset target, otherwise all other calls like Response.Redirect will open in a new tab, which might be not what you want.
Instead of loading a stream into a byte array and writing it to the response stream, you should have a look at HttpResponse.TransmitFile
Response.ContentType = "Application/pdf";
Response.TransmitFile(pathtofile);
If you want the PDF to open in a new window you would have to open the downloading page in a new window, for example like this:
View PDF
this may help
Response.Write("<script>");
Response.Write("window.open('../Inventory/pages/printableads.pdf', '_newtab');");
Response.Write("</script>");
You have to create either another page or generic handler with the code to generate your pdf. Then that event gets triggered and the person is redirected to that page.
Here I am using iTextSharp dll for generating PDF file.
I want to open PDF file instead of downloading it.
So I am using below code which is working fine for me.
Now pdf file is opening in browser ,now dowloading
Document pdfDoc = new Document(PageSize.A4, 25, 10, 25, 10);
PdfWriter pdfWriter = PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
pdfDoc.Open();
Paragraph Text = new Paragraph("Hi , This is Test Content");
pdfDoc.Add(Text);
pdfWriter.CloseStream = false;
pdfDoc.Close();
Response.Buffer = true;
Response.ContentType = "application/pdf";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.End();
If you want to download file,
add below line, after this Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;filename=Example.pdf");
you can return a FileResult from your MVC action.
*********************MVC action************
public FileResult OpenPDF(parameters)
{
//code to fetch your pdf byte array
return File(pdfBytes, "application/pdf");
}
**************js**************
Use formpost to post your data to action
var inputTag = '<input name="paramName" type="text" value="' + payloadString + '">';
var form = document.createElement("form");
jQuery(form).attr("id", "pdf-form").attr("name", "pdf-form").attr("class", "pdf-form").attr("target", "_blank");
jQuery(form).attr("action", "/Controller/OpenPDF").attr("method", "post").attr("enctype", "multipart/form-data");
jQuery(form).append(inputTag);
document.body.appendChild(form);
form.submit();
document.body.removeChild(form);
return false;
You need to create a form to post your data, append it your dom, post your data and remove the form your document body.
However, form post wouldn't post data to new tab only on EDGE browser. But a get request works as it's just opening new tab with a url containing query string for your action parameters.
Use this code. This works like a champ.
Process process = new Process();
process.StartInfo.UseShellExecute = true;
process.StartInfo.FileName = outputPdfFile;
process.Start();
I trying to export an HTML table named Table that is dynamically binded to ViewData.Model in C#. I have a method called export that is called based on another method's actions. so everything before that is set up.. I just don't know how to export the data to a CSV or Excel file.. So when the I step inside the Export method I don't know what next to do to export the table. Can someone help me
public void Export(List<data> List)
{
//the list is the rows that are checked and need to be exported
StringWriter sw = new StringWriter();
//I don't believe any of this syntax is right, but if they have Excel export to excel and if not export to csv "|" delimeted
for(int i=0; i<List.Count;i++)
{
sw.WriteLine(List[i].ID+ "|" + List[i].Date + "|" + List[i].Description);
}
Response.AddHeader("Content-Disposition", "attachment; filename=test.csv");
Response.ContentType = "application/ms-excel";
Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8");
Response.Write(sw);
Response.End();
}
I don't quite understand the whole "export an HTML table named Table that is dynamically binded to ViewData.Model" so I'll just ignore that and focus on your Export(List<data> list) method. Btw, you never really mentioned what was going wrong and where.
I see you had written "if they have Excel export to excel and if not export to csv" - I would personally just export it as a CSV file in both cases because excel can handle csv files no problem.
So with that in mind, here would be my export method based on your code.
public void Export(List<DataType> list)
{
StringWriter sw = new StringWriter();
//First line for column names
sw.WriteLine("\"ID\",\"Date\",\"Description\"");
foreach(DataType item in list)
{
sw.WriteLine(string.format("\"{0}\",\"{1}\",\"{2}\"",
item.ID,
item.Date,
item.Description));
}
Response.AddHeader("Content-Disposition", "attachment; filename=test.csv");
Response.ContentType = "text/csv";
Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8");
Response.Write(sw);
Response.End();
}
This is an excellent example, but I think that need a globalization modification.
String ltListSeparator = CultureInfo.CurrentUICulture.TextInfo.ListSeparator;
sw.WriteLine(string.format("{0}" + ltListSeparator + "{1}" + ltListSeparator + "{2}", item.ID, item.Date, item.Description));
I think your controller action method will need to wrap the data items in an html table which you may want to do any way you like, So your html+ data will be stored in a string and then you could do something like below- (its not exacly built for MVC but its easy to modify for it).
Response.ClearContent();
Response.AddHeader("content-disposition", attachment);
Response.ContentType = "application/ms-excel";
Response.Write(yourDataAndHtmlAsString);
Response.End();
CSV is a simple format and can be built up easily as a string.
http://en.wikipedia.org/wiki/Comma-separated_values
You could create an excel spreadsheet of what you think the end product should look like, save as CSV, open it in notepad and try and replicate it using a string builder.