آپلود همزمان چند فایل و ذخیره در بانک اطلاعاتی Asp.Net

در این مقاله با نحوه ارسال چند فایل به صورت همزمان و ذخیره آنها در بانک اطلاعاتی sql آشنا خواهید شد

آپلود همزمان چند فایل و ذخیره در بانک اطلاعاتی Asp.Net

ابتدا بانک اطلاعاتی با نام MultiUpload_DB ایجاد میکنیم

اسکریپت ساخت بانک اطلاعاتی :

USE [master]
GO
/****** Object:  Database [MultiUpload_DB]    Script Date: 12/14/2014 13:09:42 ******/
CREATE DATABASE [MultiUpload_DB] ON  PRIMARY 
( NAME = N'MultiUpload_DB', FILENAME = N'C:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\DATA\MultiUpload_DB.mdf' , SIZE = 2048KB , MAXSIZE = UNLIMITED, FILEGROWTH = 1024KB )
 LOG ON 
( NAME = N'MultiUpload_DB_log', FILENAME = N'C:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\DATA\MultiUpload_DB_log.ldf' , SIZE = 1024KB , MAXSIZE = 2048GB , FILEGROWTH = 10%)
GO
IF (1 = FULLTEXTSERVICEPROPERTY('IsFullTextInstalled'))
begin
EXEC [MultiUpload_DB].[dbo].[sp_fulltext_database] @action = 'enable'
end
GO
ALTER DATABASE [MultiUpload_DB] SET ANSI_NULL_DEFAULT OFF
GO
ALTER DATABASE [MultiUpload_DB] SET ANSI_NULLS OFF
GO
ALTER DATABASE [MultiUpload_DB] SET ANSI_PADDING OFF
GO
ALTER DATABASE [MultiUpload_DB] SET ANSI_WARNINGS OFF
GO
ALTER DATABASE [MultiUpload_DB] SET ARITHABORT OFF
GO
ALTER DATABASE [MultiUpload_DB] SET AUTO_CLOSE OFF
GO
ALTER DATABASE [MultiUpload_DB] SET AUTO_CREATE_STATISTICS ON
GO
ALTER DATABASE [MultiUpload_DB] SET AUTO_SHRINK OFF
GO
ALTER DATABASE [MultiUpload_DB] SET AUTO_UPDATE_STATISTICS ON
GO
ALTER DATABASE [MultiUpload_DB] SET CURSOR_CLOSE_ON_COMMIT OFF
GO
ALTER DATABASE [MultiUpload_DB] SET CURSOR_DEFAULT  GLOBAL
GO
ALTER DATABASE [MultiUpload_DB] SET CONCAT_NULL_YIELDS_NULL OFF
GO
ALTER DATABASE [MultiUpload_DB] SET NUMERIC_ROUNDABORT OFF
GO
ALTER DATABASE [MultiUpload_DB] SET QUOTED_IDENTIFIER OFF
GO
ALTER DATABASE [MultiUpload_DB] SET RECURSIVE_TRIGGERS OFF
GO
ALTER DATABASE [MultiUpload_DB] SET  DISABLE_BROKER
GO
ALTER DATABASE [MultiUpload_DB] SET AUTO_UPDATE_STATISTICS_ASYNC OFF
GO
ALTER DATABASE [MultiUpload_DB] SET DATE_CORRELATION_OPTIMIZATION OFF
GO
ALTER DATABASE [MultiUpload_DB] SET TRUSTWORTHY OFF
GO
ALTER DATABASE [MultiUpload_DB] SET ALLOW_SNAPSHOT_ISOLATION OFF
GO
ALTER DATABASE [MultiUpload_DB] SET PARAMETERIZATION SIMPLE
GO
ALTER DATABASE [MultiUpload_DB] SET READ_COMMITTED_SNAPSHOT OFF
GO
ALTER DATABASE [MultiUpload_DB] SET  READ_WRITE
GO
ALTER DATABASE [MultiUpload_DB] SET RECOVERY FULL
GO
ALTER DATABASE [MultiUpload_DB] SET  MULTI_USER
GO
ALTER DATABASE [MultiUpload_DB] SET PAGE_VERIFY CHECKSUM
GO
ALTER DATABASE [MultiUpload_DB] SET DB_CHAINING OFF
GO
EXEC sys.sp_db_vardecimal_storage_format N'MultiUpload_DB', N'ON'
GO
USE [MultiUpload_DB]
GO
/****** Object:  Table [dbo].[tblFiles]    Script Date: 12/14/2014 13:09:43 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
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,
 CONSTRAINT [PK_tblFiles] 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
SET ANSI_PADDING OFF
GO

 

سپس یک FileUpload و یک GridView روی صفحه قرار میدیم

    <div>
    <h3>مرجع تخصصی برنامه نویسان</h3>
    
<asp:FileUpload ID="FileUpload1" runat="server" AllowMultiple="true" />
<asp:Button ID="btnUpload" runat="server" Text="Upload" OnClick="btnUpload_Click" />
<hr />
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
<Columns>
    <asp:BoundField DataField="Name" HeaderText="File Name" />
</Columns>
</asp:GridView>
<hr/>
<a href="http://barnamenevisan.org/">www.Barnamenevisan.Org</a>
    </div>

 

و خاصیت AllowMultiple را برابر True قرار میدهیم

دقت داشته باشید این خاصیت فقط در ASP.Net.Net 4.5 وجود دارد

سپس فضاهای نام را اضافه میکنیم


using System.IO;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;

 

و کدهای کلید Upload

      foreach (HttpPostedFile postedFile in FileUpload1.PostedFiles)
            {
                string filename = Path.GetFileName(postedFile.FileName);
                string contentType = postedFile.ContentType;
                using (Stream fs = 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();
                            }
                        }
                    }
                }
            }

 

 و در لود صفحه گرید را از بانک پر میکنیم

     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();
                }
            }

 

 

نمونه هم ضمیمه کردم

موفق باشید

 

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