You are on page 1of 8

Database table creation CREATE TABLE [dbo].

[fileDet]( [ID] [int] IDENTITY(1,1) NOT NULL, [fname] [varchar](50) NULL, [fpath] [varchar](500) NULL, [desc1] [varchar](max) NULL ) ON [PRIMARY] GO Client side <table width="1000" align="center"> <tr> <td colspan="2"><asp:Label ID="Label1" runat="server" Text=""></asp:Label></ td> </tr> <tr> <td>Select File to be upload</td> <td><asp:FileUpload ID="FileUpload1" runat="server" /></td> </tr> <tr> <td>Description of the file</td> <td><asp:TextBox ID="TextBox2" runat="server"></asp:TextBox></td> </tr> <tr> <td colspan="2" align="center" class="style1"> <asp:Button ID="Button1" runat="server" Text="Upload" onclick="Button1_C lick" /> </td> </tr> <tr> <td colspan="2" height="250" align="center"> <asp:GridView ID="GridView1" runat="server" DataKeyNames="ID" AutoGenerateColumns="false" onrowcancelingedit="GridView1_RowCancelingEd it" onrowdeleting="GridView1_RowDeleting" onrowediting="GridView1_RowEditing" onrowupdating="GridView1_RowUpda ting" > <Columns> <asp:TemplateField HeaderText="File Name"> <itemtemplate> <asp:Image ID="Image1" runat="server" ImageUrl='<%#Eval("fpath") %>' /> </itemtemplate> <EditItemTemplate> <asp:FileUpload ID="FileUpload2" runat="server" /> </EditItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="Description"> <itemtemplate> <%#Eval("desc1")%> </itemtemplate> <EditItemTemplate> <asp:TextBox ID="txtdesc" runat="server" Text='<%#Eval("desc1")%

>'></asp:TextBox> </EditItemTemplate> </asp:TemplateField> <asp:CommandField HeaderText="Modify" ShowEditButton="true" EditText ="Edit"> <ControlStyle Width="50" /> </asp:CommandField> <asp:TemplateField HeaderText="Delete"> <ItemTemplate> <asp:LinkButton ID="lnkDelete" CommandName="Delete" runat="s erver" OnClientClick="return confirm('Are you sure you want to delete this recor d?');" >Delete</asp:LinkButton> </ItemTemplate> </asp:TemplateField> </Columns> </asp:GridView> </td> </tr> </table> Server side using System.Data.SqlClient; using System.Configuration; using System.Data; public partial class _Default : System.Web.UI.Page { SqlConnection sqlcon = new SqlConnection(ConfigurationManager.ConnectionStri ngs["Con"].ConnectionString); SqlCommand sqlcmd = new SqlCommand(); SqlDataAdapter da = new SqlDataAdapter(); DataTable dt = new DataTable(); String fname, fpath, desc; String spath; protected void Page_Load(object sender, EventArgs e) { Label1.Text = ""; if (!Page.IsPostBack) { LoadGrid(); } } protected void Button1_Click(object sender, EventArgs e) { if (FileUpload1.HasFile) { fname = FileUpload1.FileName; spath = @"~\Uploaded\" + FileUpload1.FileName; fpath = Server.MapPath("Uploaded"); fpath = fpath + @"\" + FileUpload1.FileName; desc = TextBox2.Text; if (System.IO.File.Exists(fpath)) { Label1.Text = "File Name already exists!"; return; }

else { FileUpload1.SaveAs(fpath); } //Store details in the SQL Server table StoreDetails(); TextBox2.Text = ""; LoadGrid(); } else { Label1.Text="Please select file!"; } } void StoreDetails() { String query; query = "insert into fileDet(fname,fpath,desc1) values('" + fname + "',' " + spath + "','" + desc + "')"; sqlcon.Open(); sqlcmd = new SqlCommand(query, sqlcon); sqlcmd.CommandType = CommandType.Text; sqlcmd.ExecuteNonQuery(); sqlcon.Close(); LoadGrid(); } void LoadGrid() { sqlcon.Open(); sqlcmd = new SqlCommand("select * from fileDet", sqlcon); da = new SqlDataAdapter(sqlcmd); dt.Clear(); da.Fill(dt); if (dt.Rows.Count > 0) { GridView1.DataSource = dt; GridView1.DataBind(); } else { GridView1.DataBind(); } sqlcon.Close(); } protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e) { GridView1.EditIndex = e.NewEditIndex; LoadGrid(); } protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditE ventArgs e) { GridView1.EditIndex = -1; LoadGrid(); } protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e) { String ID; ID = GridView1.DataKeys[e.RowIndex].Value.ToString();

sqlcmd = new SqlCommand("select * from fileDet where ID='" + ID + "'", s qlcon); sqlcon.Open(); da = new SqlDataAdapter(sqlcmd); da.Fill(dt); if (dt.Rows.Count > 0) { if (System.IO.File.Exists(Server.MapPath(dt.Rows[0][2].ToString()))) { System.IO.File.Delete(Server.MapPath(dt.Rows[0][2].ToString())); } } sqlcmd = new SqlCommand("delete from fileDet where ID='" + ID + "'", sql con); sqlcmd.ExecuteNonQuery(); sqlcon.Close(); LoadGrid(); } protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e) { GridViewRow row = GridView1.Rows[e.RowIndex]; string ID; ID = GridView1.DataKeys[e.RowIndex].Value.ToString(); FileUpload flname = (FileUpload)row.FindControl("FileUpload2"); if (flname.HasFile) { fname = flname.FileName; spath = @"~\Uploaded\" + flname.FileName; fpath = Server.MapPath("Uploaded"); fpath = fpath + @"\" + flname.FileName; if (System.IO.File.Exists(fpath)) { Label1.Text = "File Name already exists!"; return; } else { flname.SaveAs(fpath); } } else { Label1.Text = "Please select file!"; } TextBox desc1 = (TextBox)row.FindControl("txtdesc"); string query; query = "update fileDet set fname='" + fname + "',fpath='" + spath + "', desc1='" + desc1.Text + "' where ID='" + ID + "'"; sqlcon.Open(); sqlcmd = new SqlCommand(query, sqlcon); sqlcmd.CommandType = CommandType.Text; sqlcmd.ExecuteNonQuery(); sqlcon.Close();

GridView1.EditIndex = -1; LoadGrid(); } }

-------------------------------<!-- File upload server control --> <asp:FileUpload ID="upImage" runat="server"/> <br /> <!-- Client Side Required Field Validator for the File Upload server control --> <!-- Making sure the form is not submitted unless a file has been selected --> <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="upImage" ErrorMessage="Please select a file first!" SetFocusOnError="True" Display="Static" style="font-size: small" > </asp:RequiredFieldValidator> <br /> <!-- This is the Upload Submit Button to initiate the upload process --> <asp:Button ID="btnAdd" Text="Upload Image" OnClick="btnAdd_Click" runat="server" /> <!-- This Label displays the upload success or error message --> <asp:Label ID="lblMsg" runat="server" style="color: #FF0000; font-size: small;" /> <br /> <!-- This Label displays the uploaded file's type i.e. JPG, PNG etc. --> <asp:Label id="lblFileContentType" runat="server" style="color: #808080;font-size: small;" /> <br />

<!-- This Label displays the uploaded file's size in KB --> <asp:Label id="lblFileSize" runat="server" style="color: #808080;font-size: small;" /> <br /> <!-- This label displays the uploaded file's location on the server relative to the root --> <asp:Label id="lblFileLocation" runat="server" style="color: #808080;font-size: small;" /> <br /> <!-- This is the DataList that displays all uploaded images present in the Uploa dImages folder --> <!-- Take a look at the subprocedure on top "display uploaded images" to underst and how it works --> <!-- Notice below how the Substring property is used to truncate the image names --> <asp:DataList ID="dlstImages" RepeatColumns="6" runat="server"> <ItemTemplate> <asp:Image ID="Image1" ImageUrl='<%# Eval("Name", "~/UploadImages/{0}") %>' Style="width: 100px; margin:5px;" runat="server" /> <br /> <asp:Label ID="Label1" runat="server" Text='<%#Eval("Name").Substring(0, 15) & " ..."%>' ToolTip='<%#Eval("Name")%>' style="color: #808080;font-size: x-small" > </asp:Label> </ItemTemplate> </asp:DataList> '.......................File Upload Button Click Event Start.................... ... 'create subprocedure for upload button click event 'if the file upload field is not empty then 'declare the maximum allowable file size as whatever bytes 'declare a variable fileSize and set it equal to the file size of the uploading image 'if the file exceeds the maximum allowable size then 'end the upload and display the warning message 'else 'declare the GUID and set it equal to GUID function created below 'if the file extension complies with CheckFileType function then 'declare the upload file path and set it equal to the name of the folder & GUID & file name 'save the image to the file path 'display upload success message

'display file type extension 'display file size 'display the location of the saved file 'else 'display upload aborted message 'display a zero for all other labels 'end all if statements 'end subprocedures Sub btnAdd_Click(ByVal sender As Object, ByVal e As EventArgs ) If (upImage.HasFile) Then Dim maxFileSize As Integer = 1024000 'adjust max. file size as needed Dim fileSize As Integer = upImage.PostedFile.ContentLength If fileSize > maxFileSize Then lblMsg.Text = "File size exceeded the maximum limit of " & maxFileSi ze / 1024 & " Kb." Else Dim strGuid = fnGuid() If (CheckFileType(upImage.FileName)) Then Dim filePath As String = "~/UploadImages/" & strGuid & upImage.F ileName upImage.SaveAs(MapPath(filePath)) lblMsg.Text = "File Upload Success!" lblFileContentType.Text = "File type: " & upImage.PostedFile.Con tentType lblFileSize.Text = "File size: " & CStr(upImage.PostedFile.Conte ntLength / 1024) & " Kb" lblFileLocation.Text = "File Location: /UploadImages/" & strGuid & upImage.FileName Else lblMsg.Text = "Wrong file type! Upload Aborted." lblFileContentType.Text = "File type: 0" lblFileSize.Text = "File size: 0" lblFileLocation.Text = "File Location: 0" End If End If End If End Sub '.......................File Upload Button Click Event End...................... . '................Function To Check For Valid File Extension Start............... . 'declare a function as true or false boolean to check for file type extension to be allowed 'declare a variable named "ext" as a string and set it equal to the extention of the file to be uploaded 'if this file extension matches .gif .png .jpg or .jpeg then set the boolean to True (allow it) 'otherwise set the boolean to False (do not allow it) 'end the conditional statement 'end the function Function CheckFileType(ByVal fileName As String) As Boolean Dim ext As String = Path.GetExtension(fileName) Select Case ext.ToLower() Case ".gif" ' add or remove file types as needed Return True Case ".png" Return True Case ".jpg" Return True Case ".jpeg"

Return True Case Else Return False End Select End Function '................Function To Check For Valid File Extension End................ '..................Function To Create GUID For File Name Start................. 'declare a function to create a GUID based on the current date and time to be ad ded to the _ 'file extension of the uploaded file so as to make it unique. 'declare a variable named strGuid and set it equal to nothing for now 'using the try exception handling, set the strGuid variable equal to current dat e and time 'if there is a problem creating the GUID, throw an exception 'end try 'return the generated GUID 'end the function Function fnGuid() As String Dim strGuid As String = "" Try With Today strGuid = .Year & .Month & .Day & Now.Hour & Now.Minute & Now.Second End With Catch ex As Exception Throw ex End Try Return strGuidEnd Function '..................Function To Create GUID For File Name End................. '................Subprocedure To Display Uploaded Images Start............... 'create a sub procedure to display uploaded images 'declare a variable named upfolder and set it equal to the path of the uploaded images folder 'declare a variable named dir as the directory info of the uploaded images folde r 'create a datasource from the contents of this directory/folder 'and bind to each image in the folder Sub Page_PreRender() Dim upFolder As String = MapPath("~/UploadImages/") Dim dir As New DirectoryInfo(upFolder) dlstImages.DataSource = dir.GetFiles() dlstImages.DataBind() End Sub'................Subprocedure To Display Uploaded Images End............. ..

You might also like