这个问题其实就是图片的上传与下载功能的实现 我这写有两个方法 没有使用三层 就是简单的字符串的拼接
这个是文件上传的方法 对图片也适用- private bool UploadFileToDB(string fileName)
- {
- string cnnString = "server=.;database=LargeDataDB;uid=sa;pwd=123456";
- string cmdText = "usp_Videos_Insert";
- SqlConnection cnn = new SqlConnection(cnnString);
- cnn.Open();
- SqlCommand cmd = new SqlCommand();
- cmd.Connection = cnn;
- cmd.CommandText = cmdText;
- cmd.CommandType = CommandType.StoredProcedure;
- cmd.Parameters.Add("@FileName", SqlDbType.VarChar).Value = fileName.Substring(fileName.LastIndexOf(@"\")+1);
-
- FileStream stream = new FileStream(fileName, FileMode.Open);
- byte[] buffer = new byte[stream.Length];
- stream.Read(buffer, 0, buffer.Length);
- stream.Close();
- cmd.Parameters.Add("@Data", SqlDbType.Image).Value = buffer;
- int rowCount = cmd.ExecuteNonQuery();
- cnn.Close();
- if (rowCount > 0)
- {
- return true;
- }
- else
- {
- return false;
- }
- }
复制代码 那个数据库就是你所要上传图片的数据库 文件的全路径 可以通过 OpenFileDialog控件进行获取
然后是下载功能- private string DownFileFromDB()
- {
- string cnnString = "server=.;database=LargeDataDB;uid=sa;pwd=123456";
- string cmdText = "select FileName,Data from Videos";
- SqlConnection cnn = new SqlConnection(cnnString);
- cnn.Open();
- SqlCommand cmd = new SqlCommand();
- cmd.Connection = cnn;
- cmd.CommandText = cmdText;
- cmd.CommandType = CommandType.Text;
-
- SqlDataReader reader = cmd.ExecuteReader();
- string fileName = string.Empty;
- byte[] buffer = null;
- while (reader.Read())
- {
- fileName = (string)reader["FileName"];
- fileName = "D:\\" + fileName;
- buffer = (byte[])reader["Data"];
- FileStream stream = new FileStream(fileName, FileMode.Create);
- stream.Write(buffer,0,buffer.Length);
- stream.Close();
- }
- return fileName;
- }
复制代码 |