1
目前我正在使用ASP.NET MVC 3項目。我需要將文本(.txt)文件作爲Blob存儲到MySQL中。 MySQL對我來說是新的。將.txt文件作爲Blob從ASP.Net存儲到Mysql MVC3
目前我正在使用ASP.NET MVC 3項目。我需要將文本(.txt)文件作爲Blob存儲到MySQL中。 MySQL對我來說是新的。將.txt文件作爲Blob從ASP.Net存儲到Mysql MVC3
應該像this(的ConnectionString應修改):
string filePath = @"C:\\MyFile.ext";
//A stream of bytes that represnts the binary file
FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
//The reader reads the binary data from the file stream
BinaryReader reader = new BinaryReader(fs);
//Bytes from the binary reader stored in BlobValue array
byte[] BlobValue = reader.ReadBytes((int)fs.Length);
fs.Close();
reader.Close();
SqlConnection BlobsDatabaseConn = new SqlConnection("Data Source = .; Initial Catalog = BlobsDatabase; Integrated Security = SSPI");
SqlCommand SaveBlobeCommand = new SqlCommand();
SaveBlobeCommand.Connection = BlobsDatabaseConn;
SaveBlobeCommand.CommandType = CommandType.Text;
SaveBlobeCommand.CommandText = "INSERT INTO BlobsTable(BlobFileName, BlobFile)" + "VALUES (@BlobFileName, @BlobFile)";
SqlParameter BlobFileNameParam = new SqlParameter("@BlobFileName", SqlDbType.NChar);
SqlParameter BlobFileParam = new SqlParameter("@BlobFile", SqlDbType.Binary);
SaveBlobeCommand.Parameters.Add(BlobFileNameParam);
SaveBlobeCommand.Parameters.Add(BlobFileParam);
BlobFileNameParam.Value = filePath.Substring(filePath.LastIndexOf("\\") + 1);
BlobFileParam.Value = BlobValue;
try
{
SaveBlobeCommand.Connection.Open();
SaveBlobeCommand.ExecuteNonQuery();
MessageBox.Show(BlobFileNameParam.Value.ToString() + " saved to database.","BLOB Saved", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch(Exception ex)
{
MessageBox.Show(ex.Message, "Save Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
SaveBlobeCommand.Connection.Close();
}
看看: