Open button do not works properly in downloading with a linkbutton - asp.net

There is a section in my site that users can download files. I want that As users push the download button and hit "Open" button instead of "save" button, the download get open with it's own program. For example a pdf file should not en with ms word. Now my problem is that, as a user open the file an XML extension will be added to the download URL!!
For example it should be:
www.mysite.com/inputfile/12.dox
but instead of that, it goes for
www.mysite.com/inputfile/12.dox.xml
Here is my cod:
protected void LinkButton1_Command(object sender, CommandEventArgs e)
{
int idx = Convert.ToInt32(e.CommandArgument);
string Manuscript = GridView2.DataKeys[idx].Value.ToString();
string fileName = System.IO.Path.GetFileName(Manuscript);
string contenttype = String.Empty;
string ext = Path.GetExtension(fileName);
Response.ClearContent();
Response.ClearHeaders();
switch (ext)
{
case ".doc":
contenttype = "application/msword";
break;
case ".docx":
contenttype = "application/msword";
break;
case ".xls":
contenttype = "application/msexcel";
break;
case ".xlsx":
contenttype = "application/msexcel";
break;
case ".jpg":
contenttype = "image/jpg";
break;
case ".png":
contenttype = "image/png";
break;
case ".gif":
contenttype = "image/gif";
break;
case ".pdf":
contenttype = "application/pdf";
break;
}
Response.ContentType = contenttype;
Response.AppendHeader("Content-Disposition", "attachment; filename=" + fileName);
Response.TransmitFile(Server.MapPath(Manuscript));
Response.End();
}

Related

How to open a file with it's own program with a linkbutton

I have developed a website using Asp.net. In a section of my program users need to download some variable files. (Jpeg,Pdf,doc,docx...) As they push the download button and hit "Open" button instead of "save" button, the file will open with Adobe Acrobat. The problem is that if it is a word file, again it will be open with Adobe Acrobat!
How can i avoid this and each file open with it's own program?
I used this cod in my behind cod:
protected void LinkButton1_Command(object sender, CommandEventArgs e)
{
int idx = Convert.ToInt32(e.CommandArgument);
string Manuscript = GridView2.DataKeys[idx].Value.ToString();
string fileName = System.IO.Path.GetFileName(Manuscript);
Response.Clear();
Response.ContentType = "application/pdf";
Response.AppendHeader("Content-Disposition", "attachment; filename=" + fileName);
Response.TransmitFile(Server.MapPath(Manuscript));
Response.End();
}
Like this :
string ext = System.IO.Path.GetExtension(this.File1.PostedFile.FileName);
string contenttype = String.Empty;
OR
string ext = Path.GetExtension(filename);
switch(ext)
{
case ".doc":
contenttype = "application/vnd.ms-word";
break;
case ".docx":
contenttype = "application/vnd.ms-word";
break;
case ".xls":
contenttype = "application/vnd.ms-excel";
break;
case ".xlsx":
contenttype = "application/vnd.ms-excel";
break;
case ".jpg":
contenttype = "image/jpg";
break;
case ".png":
contenttype = "image/png";
break;
case ".gif":
contenttype = "image/gif";
break;
case ".pdf":
contenttype = "application/pdf";
break;
}
Use
FileInfo fInfo = new FileInfo(fileName);
string fileExtn = fInfo.Extension;

How do display the word document in asp.net page retrieved from SQL Server database

How do display a Word document on an asp.net page retrieved from a SQL Server database table?
I have uploaded the word document into database, please see the code,
Now I want to display the word document details in gridview, when I click the word document name in the gridview then the word document should display in webpage. Please help me how to do this.
protected void btnUpload_Click(object sender, EventArgs e)
{
string filePath = FileUpload1.PostedFile.FileName;
string filename = Path.GetFileName(filePath);
string ext = Path.GetExtension(filename);
string contenttype = String.Empty;
//Set the contenttype based on File Extension
switch (ext)
{
case ".doc":
contenttype = "application/vnd.ms-word";
break;
case ".docx":
contenttype = "application/vnd.ms-word";
break;
case ".xls":
contenttype = "application/vnd.ms-excel";
break;
case ".xlsx":
contenttype = "application/vnd.ms-excel";
break;
case ".jpg":
contenttype = "image/jpg";
break;
case ".png":
contenttype = "image/png";
break;
case ".gif":
contenttype = "image/gif";
break;
case ".pdf":
contenttype = "application/pdf";
break;
}
if (contenttype != String.Empty)
{
Stream fs = FileUpload1.PostedFile.InputStream;
BinaryReader br = new BinaryReader(fs);
Byte[] bytes = br.ReadBytes((Int32)fs.Length);
//insert the file into database
string strQuery = "insert into tblFiles(Name, ContentType, Data)" +
" values (#Name, #ContentType, #Data)";
SqlCommand cmd = new SqlCommand(strQuery);
cmd.Parameters.Add("#Name", SqlDbType.VarChar).Value = filename;
cmd.Parameters.Add("#ContentType", SqlDbType.VarChar).Value = contenttype;
cmd.Parameters.Add("#Data", SqlDbType.Binary).Value = bytes;
InsertUpdateData(cmd);
lblMessage.ForeColor = System.Drawing.Color.Green;
lblMessage.Text = "File Uploaded Successfully";
}
else
{
lblMessage.ForeColor = System.Drawing.Color.Red;
lblMessage.Text = "File format not recognised." +
" Upload Image/Word/PDF/Excel formats";
}
}
private Boolean InsertUpdateData(SqlCommand cmd)
{
SqlConnection con = new SqlConnection("user id=sa;password=123;database=Shashank;data source=Shashank");
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
try
{
con.Open();
cmd.ExecuteNonQuery();
return true;
}
catch (Exception ex)
{
Response.Write(ex.Message);
return false;
}
finally
{
con.Close();
con.Dispose();
}
}
To my knowledge you have to convert the word document to .html to display it in a web page itself. You can check out this article that shows you how to do it. http://www.c-sharpcorner.com/UploadFile/munnamax/WordToHtml03252007065157AM/WordToHtml.aspx
I guess what I would do is convert the ms doc file to HTML at upload and then store that along with the .doc or .docx. The HTML you would select and display it in an iframe and the actual .doc file you could use if the user wanted to download it.

uploading more than of 1mb is not possible

i have used below structure for my table in database. i can not upload files more than of 1mb in the database, please help what is the problem.
fileid(int), FileName(varchar(100)), ContentType (varchar(75)), data varbinary(MAX)
protected void btnUpload_Click(object sender, EventArgs e)
{
// Read the file and convert it to Byte Array
string filePath = FileUpload1.PostedFile.FileName;
string filename = Path.GetFileName(filePath);
string ext = Path.GetExtension(filename);
string contenttype = String.Empty;
//Set the contenttype based on File Extension
switch (ext)
{
case ".doc":
contenttype = "application/vnd.ms-word";
break;
case ".docx":
contenttype = "application/vnd.ms-word";
break;
case ".xls":
contenttype = "application/vnd.ms-excel";
break;
case ".xlsx":
contenttype = "application/vnd.ms-excel";
break;
case ".jpg":
contenttype = "image/jpg";
break;
case ".png":
contenttype = "image/png";
break;
case ".gif":
contenttype = "image/gif";
break;
case ".pdf":
contenttype = "application/pdf";
break;
}
if (contenttype != String.Empty)
{
Stream fs = FileUpload1.PostedFile.InputStream;
BinaryReader br = new BinaryReader(fs);
Byte[] bytes = br.ReadBytes((Int32)fs.Length);
//insert the file into database
Transmittallistfortest transmittalList = (Transmittallistfortest)DetailsView1.FindControl("Transmittallistfortest1");
GridView g3 = transmittalList.FindControl("GridViewTtransmittals") as GridView;
foreach (GridViewRow di in g3.Rows)
{
if (di.RowType == DataControlRowType.DataRow)
{
RadioButton rad = di.FindControl("RadioButton1") as RadioButton;
//Giving Error:Object reference not set to an instance of an object.
rad.CheckedChanged += new EventHandler(MyCheckedChangeEventHandler);
if (rad != null && rad.Checked)
{
var w = di.RowIndex;
string s = ((HyperLink)di.Cells[1].Controls[0]).Text;
var tr = from transmittal in _DataContext.tbltransmittalNos
where transmittal.TRANSMITTAL == s
select transmittal.TransID;
int _transid = tr.SingleOrDefault();
// int _transid = Convert.ToInt32(tr.SingleOrDefault());
Label1.Text = _transid.ToString();
Label2.Text = s;
}
}
}
tblFile fn = new tblFile();
fn.DocId = _DocID;
fn.TransId = Convert.ToInt32(Label1.Text);
fn.FileName = filename;
fn.ContentType = contenttype;
fn.Data = bytes;
// BookAuthor bookAuthor = new BookAuthor();
_DataContext.tblFiles.InsertOnSubmit(fn);
_DataContext.SubmitChanges();
//doctranscon.TransmitToConid = Convert.ToInt32(ddlTransmittaltoCon.SelectedValue);
lblMessage.ForeColor = System.Drawing.Color.Green;
lblMessage.Text = "File Uploaded Successfully";
// Update display
DisplayDocument();
}
}
You are not sharing your specific error but this is likely the cause. Increase the maxRequestLength size in your web.config file. The default is 4096 KB (4 MB).
<configuration>
<system.web>
<httpRuntime maxRequestLength="size in kbytes"
...
/>
Allocating an array size of data will, eventually, fail. Look into streaming semantics.
Check your configured maxRequestLength

icon of uploaded file in gridview when file has saved in database

before i have a question about (icon of uploaded file in gridview) and recieved below code.
this code seems that is for when we save files in the server.
now if we save files in database how i have to change the code.
using System.Drawing;
using System.IO;
public string GetIconFromFile()
{
Icon ic = Icon.ExtractAssociatedIcon(Server.MapPath (".")+"/Files/Test.txt");
string imagePath=Server.MapPath(".") + "/Images/Test.ico";
if (ic != null)
{
using (FileStream stream = new FileStream(imagePath, FileMode.OpenOrCreate))
{
ic.Save(stream);
}
}
return imagePath ;
}
protected void GridViewEfile_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
System.Web.UI.WebControls.Image img = new System.Web.UI.WebControls.Image();
img = (System.Web.UI.WebControls.Image)e.Row.FindControl("Image1");
img.ImageUrl = GetIconFromFile();
}
}
.aspx
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Image ID="Image1" runat="server" />
<asp:LinkButton ID="LinkButton1" runat="server" OnCommand="LinkButton1_Command" CommandName="Download" CommandArgument='<%#Eval("FileID")%>'><%#Eval("FileName")%></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
the code for upload button when i want to save in the database is like below please help what change in function (GetIconFromFile()) , special when we need filename.ico
protected void btnUpload_Click(object sender, EventArgs e)
{
// Read the file and convert it to Byte Array
string filePath = FileUpload1.PostedFile.FileName;
string filename = Path.GetFileName(filePath);
string ext = Path.GetExtension(filename);
string contenttype = String.Empty;
//Set the contenttype based on File Extension
switch (ext)
{
case ".doc":
contenttype = "application/vnd.ms-word";
break;
case ".docx":
contenttype = "application/vnd.ms-word";
break;
case ".xls":
contenttype = "application/vnd.ms-excel";
break;
case ".xlsx":
contenttype = "application/vnd.ms-excel";
break;
case ".jpg":
contenttype = "image/jpg";
break;
case ".png":
contenttype = "image/png";
break;
case ".gif":
contenttype = "image/gif";
break;
case ".pdf":
contenttype = "application/pdf";
break;
}
if (contenttype != String.Empty)
{
Stream fs = FileUpload1.PostedFile.InputStream;
BinaryReader br = new BinaryReader(fs);
Byte[] bytes = br.ReadBytes((Int32)fs.Length);
//insert the file into database
You have to change function GetIconFromFile where you have to write code for
Saving icon file in the database.
For saving image refer this
Display the image from database into gridview
For Displaying in gridview refer this

Download PDF Document on Save as dialog

I am using following code for downloading PDF document in save as mode but there is a problem in IE,
anyone can resolve this prohlem?
private void DownloadFile(string fname, bool forceDownload)
{
string path = MapPath(fname);
string name = Path.GetFileName(fname);
string ext = Path.GetExtension(fname);
string type = "";
Response.ClearHeaders();
Response.ClearContent();
// set known types based on file extension
if (ext != null)
{
switch (ext.ToLower())
{
case ".htm":
case ".html":
type = "text/HTML";
break;
case ".txt":
type = "text/plain";
break;
case ".pdf":
type = "application/pdf";
break;
case ".doc":
case ".docx":
case ".rtf":
type = "Application/msword";
break;
}
}
if (forceDownload)
{
Response.AppendHeader("content-disposition", "attachment; filename=" + name);
}
if (type != "")
{
Response.ContentType = type;
Response.WriteFile(path);
Response.End();
}
}
thanks
Asim Hashmi
Maybe because you're using SSL?
check this: http://support.microsoft.com/kb/316431

Resources