创建表
CREATE
TABLE
[
FileTable
]
(
[
FileID
]
[
int
]
IDENTITY
(
1
,
1
)
NOT
NULL
,
[
FileData
]
[
image
]
,
[
FileContentType
]
[
varchar
]
(
50
) ,
[
FileDescription
]
[
varchar
]
(
200
) ,
[
FileSize
]
[
int
]
NULL
)
页面代码
<
h3
>
保存文件到SQL Server数据库示例
</
h3
>
请选择要上传的文件:
<
input
id
="UP_FILE"
type
="file"
size
="24"
name
="UP_FILE"
runat
="server"
>
<
br
>
<
br
>
请输入文件说明:
<
asp:textbox
id
="txtDescription"
Runat
="server"
></
asp:textbox
>
<
br
>
<
br
>
<
asp:button
id
="SubmitButton"
Runat
="server"
Text
="上传文件"
Width
="239"
></
asp:button
>
<
br
>
<
br
>
<
asp:label
id
="txtMessage"
Runat
="server"
ForeColor
="red"
></
asp:label
><
br
>
<
br
>
<
br
>
上传文件事件代码
private
void
SubmitButton_Click(
object
sender, System.EventArgs e)

{
// HttpPostedFile对象,用于读取文件属性
HttpPostedFile UpFile = UP_FILE.PostedFile;

// FileLength 变量存储文件的字节大小
int FileLength = UpFile.ContentLength;

try

{
if (FileLength == 0)

{
txtMessage.Text = "<b>您未选择上传的文件</b>";
}
else

{
// 创建存储文件的临时 Byte 数组
Byte[] FileByteArray = new Byte[FileLength];

// 建立数据流对象
Stream StreamObject = UpFile.InputStream;
// 读取文件数据,FileByteArray为数据储存体,0为数据指针位置、FileLnegth为数据长度
StreamObject.Read(FileByteArray,0,FileLength);

// 数据库操作
string ConnStr = System.Configuration.ConfigurationSettings.AppSettings["ConnectionSqlServer"];
string query = "INSERT INTO FileTable (FileData, FileContentType, FileDescription, FileSize) VALUES (@FileData, @FileContentType, @FileDescription, @FileSize)";
SqlCommand myCommand = new SqlCommand(query, new SqlConnection(ConnStr));

// 添加各项参数并赋值
myCommand.Parameters.Add("@FileData", SqlDbType.Image);
myCommand.Parameters.Add("@FileContentType", SqlDbType.VarChar, 50);
myCommand.Parameters.Add("@FileDescription", SqlDbType.VarChar, 200);
myCommand.Parameters.Add("@FileSize", SqlDbType.BigInt);
myCommand.Parameters["@FileData"].Value = FileByteArray;
myCommand.Parameters["@FileContentType"].Value = UpFile.ContentType;
myCommand.Parameters["@FileDescription"].Value = txtDescription.Text;
myCommand.Parameters["@FileSize"].Value = FileLength;
// 执行数据库操作
myCommand.Connection.Open();
myCommand.ExecuteNonQuery();
myCommand.Connection.Close();

// 提示上传成功
txtMessage.Text = "<b>上传文件成功</b>";
}
}
catch (Exception ex)

{
// 使用 Label 标签显示异常
txtMessage.Text = ex.Message.ToString();
}
}
转载于:https://www.cnblogs.com/timsoft/articles/421550.html