李闽
摘要:文章介绍了在ASP.NET环境下,对于SQL server数据库,存储大型二进制对象的方法。通过HttpPostedfile类的InputStream属性获得Stream对象,用Stream对象读取欲上传文件内容。建立数据库连接,将文件存入数据库的二进制数据类型中。
关键词:二进制文件;数据库;HttpPostedfile类;Stream对象;上传
中图分类号:TP311文献标识码:A文章编号:1009-3044(2012)18-4410-02
Binary Files in the Database Storage
LI Min
(Suzhou Art, Design Technology Institute, Suzhou 215000, China )
Abstract: This paper introduces the ASP.NET environment in SQL server database to store large binary objects method. By HttpPosted file class InputStream property to a Stream object, use the Stream object to read to upload the contents of the file. Establish a database con nection, the binary data type of the file stored in the database.
Key words: binary files; database; class HttpPostedfileL; object StreamL; upload
上传到网站的文件有多种形式,有图形图像文件、声音文件、视频文件、文该文件等。这些文件基本上是保存在数据库中。文件在数据库中的存储主要有两种方式,一种是将文件的路径保存到数据库,文件保存到预先指定的位置。另一种是直接将文件以二进制形式保存到数据库中。该文主要介绍第二种保存方式。
在asp.net环境下,将二进制数据保存到数据库中,要应用到HttpPostedFile类的InputStream属性、Stream类的Read方法和Byte数据类型。
对于一个要上传的文件,用HttpPostedFile类的InputStream属性获取一个Stream对象,该对象就指向这个上传文件,可以用来读取文件的内容。
HttpPostFile hp=FileUpload1.PostedFile;//创建访问上传文件的对象
Stream sr=hp.InputStream;//创建Stream对象
从Stream对象中用Read方法读取相应的数据。
public abstract int Read(
byte[] buffer,
int offset,
int count
)
Read()方法可以把特定数量的字节读入到一个数组中(就是第一个参数buffer),返回实际读取的字节数。如果值为0,表示到了流的末尾。第二个参数是一个偏移量,用它可以要求Read操作的数据是从数组的哪个元素开始填充,而不一定是从第一个元素开始。第三个参数是要读入数组的字节数。代码如下。
HttpFileCollection MyFileCollection;
HttpPostedFile MyFile;
int FileLen;
MyFileCollection = Request.Files;
MyFile = MyFileCollection[0];
FileLen = MyFile.ContentLength;
byte[] input = new byte[FileLen];//建立byte数组
MyStream = MyFile.InputStream;//初始化stream.
MyStream.Read(input, 0, FileLen);//读文件到byte数组
for (int Loop1 = 0; Loop1 < FileLen; Loop1++)
MyString = MyString + input[Loop1].ToString();
//将数据从数组copy到字符串中
把二进制文件往数据库存储时,要先建立数据库……