从 ASP.NET 页面上传文件到数据库






3.72/5 (7投票s)
本示例将展示如何使用 C# 和 asp.net 将文件上传到 SQL Server 数据库。为了演示目的,数据库将只有
本示例将展示如何使用 C# 和 asp.net 将文件上传到 SQL Server 数据库。为了演示目的,数据库将只有一个名为 File 的表,包含以下列:FileId、Filename、Extension、ContentType、Document。FileId 作为表中的主键。
第一步,我们需要在页面中插入一个名为 txtFile 的 html 文件控件和一个提交表单的 btnSave 按钮。
<form id="frmMain" runat="server">
<div>
<input type="file" id="txtFile" title=" Browse for file which you want to save " Runat="server"/>
<input id="btnSave" type="button" value="Save" onclick="document.frmMain.submit()" />
</form>
以下代码是 File 表的创建语句
CREATE TABLE [dbo].[File](
[FileId] [int] IDENTITY(1,1) NOT NULL,
[Filename] [varchar](100) NULL,
[Extension] [varchar](8) NULL,
[ContentType] [varchar](50) NULL,
[Document] [varbinary](50) NULL,
CONSTRAINT [PK_File] PRIMARY KEY CLUSTERED
(
[FileId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
我们将使用存储过程 spFile_Add 将文件保存到 File 表中CREATE PROCEDURE spFile_Add
(
@Filename varchar(100),
@Extension varchar(8),
@ContentType varchar(50),
@Document varbinary(50)
)
AS
BEGIN
Insert Into [File](Filename, Extension, ContentType, Document)
values (@Filename, @Extension, @ContentType, @Document)
Select Scope_Identity()
END
我们将使用企业库进行数据库事务,因此我们需要添加相同的引用
Microsoft.Practices.EnterpriseLibrary.Common
Microsoft.Practices.EnterpriseLibrary.Data
System.Configuration
在代码后台文件中,我们需要添加以下代码行
using Microsoft.Practices.EnterpriseLibrary.Data;
using Microsoft.Practices.EnterpriseLibrary.Data.Sql;
using System.IO;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack)
{
if (txtFile.PostedFile != null && txtFile.PostedFile.ContentLength > 0)
{
string filename = Path.GetFileName(txtFile.PostedFile.FileName);
string extension = Path.GetExtension(filename);
string contentType = txtFile.PostedFile.ContentType;
byte[] document = new byte[txtFile.PostedFile.ContentLength];
int fileId = AddFile(filename, extension, contentType, document);
}
}
}
protected int AddFile(string filename, string extension, string contentType, byte[] document)
{
SqlDatabase sqlDatabase = new SqlDatabase
(ConfigurationManager.ConnectionStrings["dbConnString"].ConnectionString);
string sql = "spFile_Add";
SqlCommand sqlCommand = sqlDatabase.GetStoredProcCommand(sql) as SqlCommand;
Object obj = null;
try
{
sqlDatabase.AddInParameter(sqlCommand, "@Filename", SqlDbType.VarChar, filename);
sqlDatabase.AddInParameter(sqlCommand, "@Extension", SqlDbType.VarChar, extension);
sqlDatabase.AddInParameter(sqlCommand, "@ContentType", SqlDbType.VarChar, contentType);
sqlDatabase.AddInParameter(sqlCommand, "@Document", SqlDbType.VarBinary, document);
obj = sqlDatabase.ExecuteScalar(sqlCommand);
if (obj != null)
return int.Parse(obj.ToString());
else
return 0;
}
catch (Exception err)
{
throw new ApplicationException(err.Message);
}
}