Bước 1: Tạo CSDL tùy chọn, với Table như sau
CREATE TABLE [dbo].[wordFiles](
[Id] [int] IDENTITY(1,1) NOT NULL,
[name] [varchar](50) NULL,
[type] [varchar](50) NULL,
[data] [varbinary](max) NULL,
CONSTRAINT [PK_wordFiles] PRIMARY KEY CLUSTERED
(
[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
Bước 2:
Tạo Project với trang Default.aspx mặc định và dán code bên dưới vào
<form id="form1" runat="server">
<div>
<table>
<tr>
<td>
Select File
</td>
<td>
<asp:FileUpload ID="FileUpload1" runat="server" ToolTip="Select Only word File" />
</td>
<td>
<asp:Button ID="Button1" runat="server" Text="Upload" onclick="Button1_Click" />
</td>
<td>
<asp:Button ID="Button2" runat="server" Text="View Files"
onclick="Button2_Click" />
</td>
</tr>
</table>
<table><tr><td><p><asp:Label ID="Label2" runat="server" Text="label"></asp:Label> </p></td></tr></table>
<asp:GridView ID="GridView1" runat="server" Caption="Excel Files "
CaptionAlign="Top" HorizontalAlign="Justify"
DataKeyNames="id" onselectedindexchanged="GridView1_SelectedIndexChanged"
ToolTip="Word FIle DownLoad Tool" CellPadding="4" ForeColor="#333333"
GridLines="None">
<RowStyle BackColor="#E3EAEB" />
<Columns>
<asp:CommandField ShowSelectButton="True" SelectText="Download" ControlStyle-ForeColor="Blue"/>
</Columns>
<FooterStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#666666" ForeColor="White" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#C5BBAF" Font-Bold="True" ForeColor="#333333" />
<HeaderStyle BackColor="Gray" Font-Bold="True" ForeColor="White" />
<EditRowStyle BackColor="#7C6F57" />
<AlternatingRowStyle BackColor="White" />
</asp:GridView>
</div>
</form>
Sau đó vào Default.cs để dán các hàm xử lý vào
protected void Button1_Click(object sender, EventArgs e)
{
Label2.Visible = true;
string filePath = FileUpload1.PostedFile.FileName; // getting the file path of uploaded file
string filename1 = Path.GetFileName(filePath); // getting the file name of uploaded file
string ext = Path.GetExtension(filename1); // getting the file extension of uploaded file
string type = String.Empty;
if (!FileUpload1.HasFile)
{
Label2.Text = "Please Select File"; //if file uploader has no file selected
}
else
if (FileUpload1.HasFile)
{
try
{
switch (ext) // this switch code validate the files which allow to upload only PDF file
{
case ".doc":
type = "application/word";
break;
case ".docx":
type = "application/word";
break;
}
if (type != String.Empty)
{
connection();
Stream fs = FileUpload1.PostedFile.InputStream;
BinaryReader br = new BinaryReader(fs); //reads the binary files
Byte[] bytes = br.ReadBytes((Int32)fs.Length); //counting the file length into bytes
query = "insert into wordFiles (Name,type,data)" + " values (@Name, @type, @Data)"; //insert query
com = new SqlCommand(query, con);
com.Parameters.Add("@Name", SqlDbType.VarChar).Value = filename1;
com.Parameters.Add("@type", SqlDbType.VarChar).Value = type;
com.Parameters.Add("@Data", SqlDbType.Binary).Value = bytes;
com.ExecuteNonQuery();
Label2.ForeColor = System.Drawing.Color.Green;
Label2.Text = " Word File Uploaded Successfully";
}
else
{
Label2.ForeColor = System.Drawing.Color.Red;
Label2.Text = "Select Only word Files "; // if file is other than speified extension
}
}
catch (Exception ex)
{
Label2.Text = "Error: " + ex.Message.ToString();
}
}
}
Tiếp tục thêm sự kiện cho button thứ 2:
protected void Button2_Click(object sender, EventArgs e)
{
connection();
query = "Select *from WordFiles";
SqlDataAdapter da = new SqlDataAdapter(query, con);
DataSet ds = new DataSet();
da.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
con.Close();
}
Và thêm code sau để có thể dễ dàng xem các tệp tin hiện tại
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
connection();
SqlCommand com =new SqlCommand("select Name,type,data from WordFiles where id=@id", con);
com.Parameters.AddWithValue("id", GridView1.SelectedRow.Cells[1].Text);
SqlDataReader dr = com.ExecuteReader();
if (dr.Read())
{
Response.Clear();
Response.Buffer =true;
Response.ContentType = dr["type"].ToString();
Response.AddHeader("content-disposition", "attachment;filename=" + dr["Name"].ToString()); // to open file prompt Box open or Save file
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.BinaryWrite((byte[])dr["data"]);
Response.End();
}
}