我已经介绍了几种不同的方法,用于将数据插入SQL Server(For FileStream).插入FileStream对象的最佳方法是什么?下面的方法之间的主要区别是一个直接执行插入,另一个放在FileStream对象的占位符中.
一种方法是他们通过插件直接通过C#插入文档:
链接:FileStream
con.Open();
string sql = "INSERT INTO MyFsTable VALUES (@fData, @fName, default)";
SqlCommand cmd = new SqlCommand(sql, con);
cmd.Parameters.Add("@fData", SqlDbType.Image, fileData.Length).Value = fileData;
cmd.Parameters.Add("@fName", SqlDbType.NVarChar).Value = fi.Name;
cmd.ExecuteNonQuery();
con.Close();
另一种方法是他们插入一行,但是将文档(FileStream Column)留空.我必须输入一个虚拟值,因为当FileStream列为null时,我的Get File Path调用返回Null:
链接:FileStream
5: if (FileUpload1.FileContent.Length > 0)
6: {
7: SqlConnection objSqlCon = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
8: objSqlCon.Open();
9: SqlTransaction objSqlTran = objSqlCon.BeginTransaction();
10:
11: SqlCommand objSqlCmd = new SqlCommand("FileAdd",objSqlCon,objSqlTran);
12: objSqlCmd.CommandType = CommandType.StoredProcedure;
13:
14: SqlParameter objSqlParam1 = new SqlParameter("@SystemNumber", SqlDbType.Int);
15: objSqlParam1.Value = "1";
16:
17: SqlParameter objSqlParam2 = new SqlParameter("@FileType", SqlDbType.VarChar,4);
18: objSqlParam2.Value = System.IO.Path.GetExtension(FileUpload1.FileName);
19:
20: SqlParameter objSqlParamOutput = new SqlParameter("@filepath", SqlDbType.VarChar, -1);
21: objSqlParamOutput.Direction = ParameterDirection.Output;
22:
23: objSqlCmd.Parameters.Add(objSqlParam2);
24: objSqlCmd.Parameters.Add(objSqlParam1);
25: objSqlCmd.Parameters.Add(objSqlParamOutput);
26:
27:
28: objSqlCmd.ExecuteNonQuery();
29:
30: string Path = objSqlCmd.Parameters["@filepath"].Value.ToString();
31:
32: objSqlCmd = new SqlCommand("SELECT GET_FILESTREAM_TRANSACTION_CONTEXT()", objSqlCon, objSqlTran);
33:
34: byte[] objContext = (byte[])objSqlCmd.ExecuteScalar();
35:
36:
37: SqlFileStream objSqlFileStream = new SqlFileStream(Path, objContext, FileAccess.Write);
38:
39: objSqlFileStream.Write(buffer, 0, buffer.Length);
40: objSqlFileStream.Close();
41:
42: objSqlTran.Commit();
解决方法:
有关如何以高效,面向流的方式上载和下载文件流的示例,请参阅FILESTREAM MVC: Download and Upload images from SQL Server.你正在追求的方法,分配一个缓冲区大小整个上传文件的大小(我假设你也在服务内容时做同样的事情)是非常低效的,你的ASP进程内存将被这么大的字节[]碎成碎片.操作.