2013-05-15 93 views
1

所以我有这样的代码:图像插入数据库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永远不会获得图像。它保持空白,并在执行存储过程时被捕获,并说我从未传过图像。我相信代码很好。我不知道为什么我无法将图像存入我的字节数组中。

+0

的代码似乎是正确的。你确定10000字节就够了吗?我试过了,它工作正常。不得不将我的小测试图片的字节数提高到400 000。 –

+0

考虑在数据库中存储文件的文件名引用,并将实际文件存储在其他位置。 –

+0

我的图像实际上只有60字节大,当我试图说只是字节[]原料,然后几个留置后来使用原料,它只是跳过原料。所以这就是为什么我给它一个大小和实例化它更早 – dwarf

回答

0

您可以创建/定义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 
+0

无论什么原因,使用这个例子的作品。不是我只需要从varchar转换为varbinary,因为我的存储过程不像隐式转换 – dwarf

+0

代码是从msdn http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.fileupload。 postedfile.aspx – Amitd

0

我做的是我得到的ByteArray

public Byte[] GetArrayFromFile(string path) 
{ 
    Byte[] data = null 

    FileInfo fileInf = new FileInfo(path); 
    long numBytes = fileInf.Length; 

    FileStream fStream = nw FileStream(path, FileMode.Open, FileAccess.Read); 

    BinaryReader bReader = new BinaryReader(fStream); 

    data = bReader.ReadBytes((int)numBytes); 
    return data; 
} 

然后在数据库中存储正确使用实体框架(它应该,如果你的DAL插入您的正确的对象在数据库中工作)。

+2

另请注意'FileStream'是'IDisposable',所以你可能想要处理它或者把它放在'using'块中。 –

+0

这仍然给我同样的问题。使用所提供的答案中的代码,数据保持大小为0,没有任何数据写入它。 – dwarf

+0

你是否设法获得numBytes的值? –