icon of uploaded file in gridview when file has saved in database - asp.net

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

Related

Open a file on the click of button from a textbox path in Asp.net

Using Asp.net, I'm reading a path and showing all the files path in a runtime created Text box/boxes as follows:
These Files not just pdf but ppt, doc,docx, etc and the code which i used is:
protected void SearchButton_Click(object sender, EventArgs e)
{
string dir = #"D:\file path\";
SearchResultPanel.Visible = true;
try
{
//Set the current directory.
Directory.SetCurrentDirectory(dir);
//search all files in path
string[] directoryEntries = Directory.GetFiles(dir, "*.*", SearchOption.AllDirectories);
int fill = directoryEntries.Length - 1;
//Total count of files & Decoration
SearchResultPanel.Controls.Add(new LiteralControl("<br />"));
Label leb = new Label();
SearchResultPanel.Controls.Add(new LiteralControl("The total files count: "));
leb.Text = directoryEntries.Length.ToString();
this.SearchResultPanel.Controls.Add(leb);
SearchResultPanel.Controls.Add(new LiteralControl("<hr />"));
//retriving the files in new labels
for (int i = 0; i < fill; i++)
{
TextBox NewText = new TextBox();
NewText.BorderStyle = BorderStyle.NotSet;
NewText.TextMode = TextBoxMode.MultiLine;
NewText.Width = 380;
NewText.Height = 40;
TextBox NewTextP = new TextBox();
NewTextP.BorderStyle = BorderStyle.NotSet;
NewTextP.TextMode = TextBoxMode.MultiLine;
NewTextP.Width = 380;
NewTextP.Height = 40;
Button ButtonOpen = new Button();
ButtonOpen.Text = "Open";
//fill the text boxes with file entries
String path = directoryEntries[i];
NewText.Text = directoryEntries[i];
NewTextP.Text = "Dummy Paragraph";
**ButtonOpen.Click += OpenFile(path);**
//new line
SearchResultPanel.Controls.Add(new LiteralControl("<br />"));
//show the text box
this.SearchResultPanel.Controls.Add(NewText);
SearchResultPanel.Controls.Add(new LiteralControl(" "));
this.SearchResultPanel.Controls.Add(NewTextP);
SearchResultPanel.Controls.Add(new LiteralControl(" "));
this.SearchResultPanel.Controls.Add(ButtonOpen);
}//end of for
}//end of try
catch (DirectoryNotFoundException ex)
{
Console.WriteLine("The specified directory does not exist. {0}", ex);
}
I'm getting a problem # ButtonOpen.Click += OpenFile(path); as how to open the path associate file on the click of OPEN button.
Any Suggessions?
Please See this solution. I have tested now with sample.Please Mark as answered if you got help from this.
I hardcoded the file path. You can get it from text box and assign to filePath variable.
This is Link Button Click event. You have to use System.IO and System .NET as extra libraries, which is for Path.getExtention() and WebClient Class.
protected void LinkButton1_Click(object sender, EventArgs e)
{
string filePath = "C:\\GIHAN\\Employee Profile - Senior Engineer Technology.docx";
string fileExtention = Path.GetExtension(filePath);
WebClient client = new WebClient();
Byte[] buffer = client.DownloadData(filePath);
Response.ContentType = ReturnExtension(fileExtention);
Response.AddHeader("content-length", buffer.Length.ToString());
Response.BinaryWrite(buffer);
}
protected void Button1_Click(object sender, EventArgs e)
{
}
private string ReturnExtension(string fileExtension)
{
switch (fileExtension)
{
case ".htm":
case ".html":
case ".log":
return "text/HTML";
case ".txt":
return "text/plain";
case ".doc":
return "application/ms-word";
case ".tiff":
case ".tif":
return "image/tiff";
case ".asf":
return "video/x-ms-asf";
case ".avi":
return "video/avi";
case ".zip":
return "application/zip";
case ".xls":
case ".csv":
return "application/vnd.ms-excel";
case ".gif":
return "image/gif";
case ".jpg":
case "jpeg":
return "image/jpeg";
case ".bmp":
return "image/bmp";
case ".wav":
return "audio/wav";
case ".mp3":
return "audio/mpeg3";
case ".mpg":
case "mpeg":
return "video/mpeg";
case ".rtf":
return "application/rtf";
case ".asp":
return "text/asp";
case ".pdf":
return "application/pdf";
case ".fdf":
return "application/vnd.fdf";
case ".ppt":
return "application/mspowerpoint";
case ".dwg":
return "image/vnd.dwg";
case ".msg":
return "application/msoutlook";
case ".xml":
case ".sdxl":
return "application/xml";
case ".xdp":
return "application/vnd.adobe.xdp+xml";
default:
return "application/octet-stream";
}
}
}
}

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.

How to get value (draft.DraftId = new int();)and use in the variable

In my aspx page I have a dropdownlist when I select value "Draft Document" it gets new DraftID (identity).
Below of this dropdown list I have upload control, and gridview that like shows files when I attached.
I have used below query for datasource of gridview but I have problem in value (_DraftId)
var query = from at in _DataContext.tblAttachments
where at.DraftID == _DraftId
select at;
it is null, while I have used at the top _DraftId = (int)draft.DraftId;.
Actually I do not know how to get value draft.DraftId = new int(); and use it in the variable and use in another places of code.
Tbldraft
DraftID BIGINT IDENTITY(1,1) PRIMARY KEY
FromEmailID
Tblattachement:
AttachmentID BIGINT IDENTITY(1,1) PRIMARY KEY,
Draftid BIGINT NOT NULL REFERENCES tblDraft(DraftID),
FileName varchar(40) NOT NULL,
Aspx.cs
public partial class Draft : System.Web.UI.Page
{
private EDMSDataContext _DataContext;
private int _DraftId;
private string _filePath;
private string _filename;
private string _filename_Ext;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void ddlDraft_SelectedIndexChanged(object sender, EventArgs e)
{
_DataContext = new EDMSDataContext();
if (ddlDraft.SelectedValue == "Draft Document")
{
tblDraft draft = new tblDraft();
draft.DraftId = new int();
_DraftId = (int)draft.DraftId;
draft.FromEmailId = (Guid)Membership.GetUser().ProviderUserKey;
_DataContext.tblDrafts.InsertOnSubmit(draft);
_DataContext.SubmitChanges();
}
}
protected void btnUpload_Click(object sender, EventArgs e)
{
string filePath = FileUpload1.PostedFile.FileName;
string fullAddress = Path.GetFullPath(filePath);
_filePath = fullAddress;
string filename = Path.GetFileName(filePath);
_filename = filename.Split('.')[0];
_filename_Ext = filename;
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
// }
tblAttachment attach = new tblAttachment();
attach.DraftID = _DraftId;
attach.FileName = filename;
attach.ContentType = contenttype;
attach.Data = bytes;
attach.Exten = ext;
_DataContext.tblAttachments.InsertOnSubmit(attach);
_DataContext.SubmitChanges();
//doctranscon.TransmitToConid = Convert.ToInt32(ddlTransmittaltoCon.SelectedValue);
var query = from at in _DataContext.tblAttachments
where at.DraftID == _DraftId
select at;
GridViewEfile.DataSource = query;
GridViewEfile.DataBind();
}
}
Looking quickly at the source, I'd suggest rearranging the SelectedIndexChanged method to allocate the id after the SubmitChanges. It's only after the save that the id will become available; before this, it doesn't exist.
protected void ddlDraft_SelectedIndexChanged(object sender, EventArgs e)
{
_DataContext = new EDMSDataContext();
if (ddlDraft.SelectedValue == "Draft Document")
{
tblDraft draft = new tblDraft();
draft.FromEmailId = (Guid)Membership.GetUser().ProviderUserKey;
_DataContext.tblDrafts.InsertOnSubmit(draft);
_DataContext.SubmitChanges();
_DraftId = (int)draft.DraftId;
}
}
Also, as a side-note, I'd consider whether a) some error handling might be useful in the above snippet, and b) whether a better solution might not be found to replace the global variable for storing _DraftId.
HTH.

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

Resources