【转贴】将文件转成数据流存入数据库的例子代码

Stream fileDataStream = MyFile.PostedFile.InputStream;

   //得到文件大小
   int fileLength = MyFile.PostedFile.ContentLength;

   //创建数组
   byte[] fileData = new byte[fileLength];

   //把文件流填充到数组
   fileDataStream.Read(fileData,0,fileLength);

   //得到文件名字
   string fileTitle = MyFileName.Value;

   //得到文件类型
   string fileType = MyFile.PostedFile.ContentType;

   //构建数据库连接,SQL语句,创建参数
   SqlConnection connection = new SqlConnection(“Server=127.0.0.1;uid=sa;pwd=gotomis;Database=shop”);
   SqlCommand command = new SqlCommand (“INSERT INTO TestFiles (MyFileName,MyFile,FileType)” +
    “VALUES (@MyFileName,@MyFile,@FileType)”, connection);

   SqlParameter paramTitle = new SqlParameter (“@MyFileName”, SqlDbType.VarChar,35);
   paramTitle.Value = fileTitle;
   command.Parameters.Add(paramTitle);

   SqlParameter paramData = new SqlParameter (“@MyFile”, SqlDbType.Image);
   paramData.Value = fileData;
   command.Parameters.Add(paramData);

   SqlParameter paramType = new SqlParameter (“@FileType”, SqlDbType.VarChar,25);
   paramType.Value = fileType;
   command.Parameters.Add(paramType);

   //打开连接,执行查询
   connection.Open();
   command.ExecuteNonQuery();
   connection.Close();

   Message.Text=”你的文件已经成功上载”;
   MyFileName.Value = “”;

点赞