[英]insert an image into a database c#
所以我有这个代码:
if ((uplImage.FileName != ""))
{
byte[] raw = new byte[10000];
//to allow only jpg gif and png files to be uploaded.
string extension = Path.GetExtension(uplImage.PostedFile.FileName.ToUpper());
if (((extension == ".JPG") || ((extension == ".GIF") || (extension == ".PNG"))))
{
DALBio bio = new DALBio();
FileStream fs = new FileStream(uplImage.PostedFile.FileName, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.Read);
fs.Read(raw, 0, System.Convert.ToInt32(fs.Length));
bio.PlayerID = Session["playerID"].ToString();
bio.Pending = 'Y';
bio.Photo = raw;
DALBio.insertImage(bio);
}
}
当我尝试这个时,流没有读取图像。 raw
永远不会得到图像。 它保持为空,并在执行存储过程时被捕获,说我从未传递过图像。 我相信代码很好。 我不知道为什么我无法将图像放入我的字节数组中。
我所做的是得到ByteArray
:
public Byte[] GetArrayFromFile(string path)
{
Byte[] data = null;
FileInfo fileInf = new FileInfo(path);
long numBytes = fileInf.Length;
using (FileStream fStream = new FileStream(path, FileMode.Open, FileAccess.Read))
{
BinaryReader bReader = new BinaryReader(fStream);
data = bReader.ReadBytes((int)numBytes);
}
return data;
}
然后它使用实体框架正确存储在数据库中(如果您的DAL
将您的对象正确插入数据库中,它应该可以工作)。
您可以将raw
数组创建/定义为
FileStream fs = new FileStream(uplImage.PostedFile.FileName,
FileMode.OpenOrCreate, FileAccess.ReadWrite,
FileShare.Read);
raw = new byte[fs.Length];
// same code as above..
您也可以尝试类似的代码
System.IO.Stream myStream;
Int32 fileLen;
// Get the length of the file.
fileLen = uplImage.PostedFile.ContentLength;
// Create a byte array to hold the contents of the file.
Byte[] input = new Byte[fileLen];
// Initialize the stream to read the uploaded file.
myStream = uplImage.FileContent;
// Read the file into the byte array.
myStream.Read(input, 0, fileLen);
// input will hold the byte array
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.