آپلود فایل و ذخیره سازی با فرمت Binary

دوشنبه 25 مرداد 1395

در این مقاله قصد داریم که شما را با بارگذاری فایل و ذخیره سازی آن در Database با فرمت Binary آشنا کنیم.

آپلود فایل و ذخیره سازی با فرمت Binary

ما خواهیم دید که چگونه فایل ها را بارگذاری میکنیم.(که فایل ها میتوانند اعم از PDFs, Zip files باشند.) و در database  ذخیره میکنیم و چگونه انها رابازیابی و download مینماییم.

این کد برای زمانی که نیاز دارید به بارگذاری documents مختلف مفید خواهد بود.

ممکن است در هنگام دیدن یک فایل نیاز به download  آن برای دیدن متن آن دارید. که باید به صورت  فرمت باینری (Binary format) ذخیره شود.

مرحله 1: ساختن table

 

CREATE TABLE [dbo].[tblFiles](  
    [id] [int] IDENTITY(1,1) NOT NULL,  
    [Name] [varchar](50) NOT NULL,  
    [ContentType] [nvarchar](200) NOT NULL,  
    [Data] [varbinary](max) NOT NULL  
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]  

 

مرحله 2:

Open Visual Studio File->New Website

 

 

 

<asp:GridView ID="GridView1" runat="server"   
              
            AutoGenerateColumns="false" CssClass="table">  
            <Columns>  
                <asp:BoundField DataField="Name" HeaderText="File Name" />  
                <asp:TemplateField ItemStyle-HorizontalAlign="Center">  
                    <ItemTemplate>  
                        <asp:LinkButton ID="lnkDownload" runat="server" Text="Download" OnClick="DownloadFile"  
                            CommandArgument='<%# Eval("Id") %>'></asp:LinkButton>  
                    </ItemTemplate>  
                </asp:TemplateField>  
            </Columns>  
        </asp:GridView>  

 

شما خواهید دید درون Gridview که، <asp:BoundField/> مورد استفاده قرار گرفته است.

همانطور که مشاهده میکنید در Gridview  نام فایل HeaderText تعریف شده است. که در درون <Itemtemplate></Itemtemplate> شما نیاز دارید به  Link button با  ID=”lnkDownload”  و OnClick=”DownloadFile”.

بنابراین در اخر در فایل Document.aspx  داریم:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="DocumentUpload.aspx.cs" Inherits="_Default" %>  
  
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
<html xmlns="http://www.w3.org/1999/xhtml">  
<head id="Head1" runat="server">  
    <title></title>  
    <link rel="Stylesheet" href="Styles/bootstrap.min.css" style="" />  
        <link rel="Stylesheet" href="Styles/bootstrap.css" />  
</head>  
<body>  
    <form id="form1" runat="server">  
    <div class="container">  
        <asp:FileUpload ID="FileUpload1" runat="server" />  
        <asp:Button ID="btnUpload" runat="server" Text="Upload" OnClick="Upload" CssClass="btn-primary" />  
        <hr />  
        <asp:GridView ID="GridView1" runat="server"   
              
            AutoGenerateColumns="false" CssClass="table">  
            <Columns>  
                <asp:BoundField DataField="Name" HeaderText="File Name" />  
                <asp:TemplateField ItemStyle-HorizontalAlign="Center">  
                    <ItemTemplate>  
                        <asp:LinkButton ID="lnkDownload" runat="server" Text="Download" OnClick="DownloadFile"  
                            CommandArgument='<%# Eval("Id") %>'></asp:LinkButton>  
                    </ItemTemplate>  
                </asp:TemplateField>  
            </Columns>  
        </asp:GridView>  
    </div>  
    </form>  
</body>  
</html>  

 

و design هم در اخر داریم:

مرحله 3: دیدن قسمت کد CS

که اول شامل connection string در web.config است.

<connectionStrings>  
    <add name="constr" providerName="System.Data.SQlClient" connectionString="Data Source=AB-NPC1-D1A315;Initial Catalog=TEST;User ID=sa;Password=p@ssw0rd"/>  
  </connectionStrings 

 

حالا خواهیم دید که فایل upload و در database ذخیره میشود.

.

 

همانطور که در کد ملاحظه کردید متوجه شدید که چگونه ما  در table fileName ذخیره سازی را انجام دادیم.

در اینجا نوع فایل ها Words, PDF, imageو... هستند.  ما فایل های ارسالی را توسط Stream به صورت binary format ذخیره میکنیم.

using (Stream fs = FileUpload1.PostedFile.InputStream)  
        {  
            using (BinaryReader br = new BinaryReader(fs))  
            {  
                byte[] bytes = br.ReadBytes((Int32)fs.Length);  
  
byte[] bytes = br.ReadBytes((Int32)fs.Length);  
This line of code is reading the bytes .  
  string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;  
                using (SqlConnection con = new SqlConnection(constr))  
                {  
                    string query = "insert into tblFiles values (@Name, @ContentType, @Data)";  
                    using (SqlCommand cmd = new SqlCommand(query))  
                    {  
                        cmd.Connection = con;  
                        cmd.Parameters.AddWithValue("@Name", filename);  
                        cmd.Parameters.AddWithValue("@ContentType", contentType);  
                        cmd.Parameters.AddWithValue("@Data", bytes);  
                        con.Open();  
                        cmd.ExecuteNonQuery();  
                        con.Close();

در اینجا فایل ها را بوسیله cmd.Parameters.AddWithValue(“@FieldName”,FileName),  وارد  database کردیم.

کد های زیر برای دانلود میباشد:

 

در اینجا ما byte ها را میخوانیم که باید در database ذخیره شوند.

کد پایانی CS:

using System;  
using System.Web;  
using System.Web.Security;  
using System.Web.UI;  
using System.Web.UI.WebControls;  
using System.Web.UI.WebControls.WebParts;  
using System.Web.UI.HtmlControls;  
using System.IO;  
using System.Data;  
using System.Data.SqlClient;  
using System.Configuration;  
  
  
public partial class _Default : System.Web.UI.Page  
{  
  
    protected void Page_Load(object sender, EventArgs e)  
    {  
        if (!IsPostBack)  
        {  
            BindGrid();  
        }  
    }  
    private void BindGrid()  
    {  
        string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;  
        using (SqlConnection con = new SqlConnection(constr))  
        {  
            using (SqlCommand cmd = new SqlCommand())  
            {  
                cmd.CommandText = "select Id, Name from tblFiles";  
                cmd.Connection = con;  
                con.Open();  
                GridView1.DataSource = cmd.ExecuteReader();  
                GridView1.DataBind();  
                con.Close();  
            }  
        }  
    }  
    protected void Upload(object sender, EventArgs e)  
    {  
        string filename = Path.GetFileName(FileUpload1.PostedFile.FileName);  
        string contentType = FileUpload1.PostedFile.ContentType;  
        using (Stream fs = FileUpload1.PostedFile.InputStream)  
        {  
            using (BinaryReader br = new BinaryReader(fs))  
            {  
                byte[] bytes = br.ReadBytes((Int32)fs.Length);  
                string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;  
                using (SqlConnection con = new SqlConnection(constr))  
                {  
                    string query = "insert into tblFiles values (@Name, @ContentType, @Data)";  
                    using (SqlCommand cmd = new SqlCommand(query))  
                    {  
                        cmd.Connection = con;  
                        cmd.Parameters.AddWithValue("@Name", filename);  
                        cmd.Parameters.AddWithValue("@ContentType", contentType);  
                        cmd.Parameters.AddWithValue("@Data", bytes);  
                        con.Open();  
                        cmd.ExecuteNonQuery();  
                        con.Close();  
                    }  
                }  
            }  
        }  
        Response.Redirect(Request.Url.AbsoluteUri);  
    }  
    protected void DownloadFile(object sender, EventArgs e)  
    {  
        int id = int.Parse((sender as LinkButton).CommandArgument);  
        byte[] bytes;  
        string fileName, contentType;  
        string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;  
        using (SqlConnection con = new SqlConnection(constr))  
        {  
            using (SqlCommand cmd = new SqlCommand())  
            {  
                cmd.CommandText = "select Name, Data, ContentType from tblFiles where Id=@Id";  
                cmd.Parameters.AddWithValue("@Id", id);  
                cmd.Connection = con;  
                con.Open();  
                using (SqlDataReader sdr = cmd.ExecuteReader())  
                {  
                    sdr.Read();  
                    bytes = (byte[])sdr["Data"];  
                    contentType = sdr["ContentType"].ToString();  
                    fileName = sdr["Name"].ToString();  
                }  
                con.Close();  
            }  
        }  
        Response.Clear();  
        Response.Buffer = true;  
        Response.Charset = "";  
        Response.Cache.SetCacheability(HttpCacheability.NoCache);  
        Response.ContentType = contentType;  
        Response.AppendHeader("Content-Disposition", "attachment; filename=" + fileName);  
        Response.BinaryWrite(bytes);  
        Response.Flush();   
        Response.End();  
    }  
}  

 

حالا فقط باید run Application کنیم:

 

 

شما نام فایل های دانلود شده را میتوانید ببینید.

حالا شروع میکنیم به upload کردن انها:

 

بیایید طول فایل ها را ببینیم:

 

 

خروجی را در زیر میبینیم:

فایل های ضمیمه

برنامه نویسان

نویسنده 3355 مقاله در برنامه نویسان

کاربرانی که از نویسنده این مقاله تشکر کرده اند

در صورتی که در رابطه با این مقاله سوالی دارید، در تاپیک های انجمن مطرح کنید