将图像插入数据库c#
所以我有这个代码:将图像插入数据库c#,c#,sql,image,blob,C#,Sql,Image,Blob,所以我有这个代码: 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") |
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);
}
}
当我尝试此操作时,流没有读取图像<代码>原始从未获取图像。它保持为空,并在执行存储过程时被捕获,表示我从未传递过映像。我相信代码是很好的。我不知道为什么我不能将图像放入字节数组 我要做的是通过数组获取
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
另请注意,
FileStream
是IDisposable
,因此您可能希望处置它或使用块将其放入中。这仍然会给我带来相同的问题。使用提供的答案中的代码,数据保持在0的大小,不会写入任何内容。代码似乎是正确的。你确定10000字节就足够了吗?我试过了,效果很好。必须为我的小测试图片将字节提升到400到000。考虑将文件名引用存储到DB中的文件中,并将实际文件存储在其他地方。我的图像实际上是60字节大,当我试图只说字节[]原始的,然后一些留置权使用RAW时,它就跳过RAW。这就是为什么我给了它一个大小,并在更早的时候对它进行了实例化,还有一个类似的问题,它可能有助于任何不能使用var raw=System.File.IO.ReadAllBytes(upimage.PostedFile.FileName)
?无论出于何种原因,使用这个示例都是有效的。不,我只需要从varchar转换为varbinary,因为我存储的进程不喜欢隐式转换代码来自msdn