[英]How Can I save image in database usoing asp.net webapi
I am working on an API.我正在研究 API。 Everything is getting done smoothly so far, but I have to save images to the database in the API.
到目前为止一切都很顺利,但我必须将图像保存到 API 中的数据库中。 Scenario, let's say I have a class of Person with three properties {Name, Age, and (byte[])Image} .
场景,假设我有一个人的class具有三个属性{Name, Age, and (byte[])Image} 。 How can add the Person's image in the database through API?
如何通过 API 将 Person 的图像添加到数据库中?
Thanks.谢谢。
public IHttpActionResult Create([FromBody] Person person) { }
To achieve that you will need to use VarBinary
in order to pass the image parameter, like in this example:为此,您需要使用
VarBinary
来传递图像参数,如下例所示:
public static void InsertByteArrayintoSqlDatabase()
{
string sampleText = "Hello World!";
byte[] byteData = Encoding.UTF8.GetBytes(sampleText);
using (SqlConnection sqlconnection = new SqlConnection(@"Data Source=.SQLExpress;
Initial Catalog=MorganDB; Integrated Security=SSPI;"))
{
sqlconnection.Open();
// create table if not exists
string createTableQuery = @"Create Table [MyTable](ID int, [BinData] varbinary(max))";
SqlCommand command = new SqlCommand(createTableQuery, sqlconnection);
command.ExecuteNonQuery();
string insertXmlQuery = @"Insert Into [MyTable] (ID,[BinData]) Values(1,@BinData)";
// Insert Byte [] Value into Sql Table by SqlParameter
SqlCommand insertCommand = new SqlCommand(insertXmlQuery, sqlconnection);
SqlParameter sqlParam = insertCommand.Parameters.AddWithValue("@BinData", byteData);
sqlParam.DbType = DbType.Binary;
insertCommand.ExecuteNonQuery();
}
Taken from https://morgantechspace.com/2014/05/how-to-store-and-read-byte-array-in-sql-server-using-csharp.html取自https://morgantechspace.com/2014/05/how-to-store-and-read-byte-array-in-sql-server-using-csharp.html
I do not recommend storing images as they are in the database.我不建议将图像存储在数据库中。 Instead, it makes much more sense to store them as files and store their name/path in the database.
相反,将它们存储为文件并将它们的名称/路径存储在数据库中会更有意义。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.