1

所以我有这个代码:

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永远不会得到图像。它保持为空,并在执行存储过程时被捕获,说我从未传递过图像。我相信代码很好。我不知道为什么我不能将图像放入我的字节数组中。

4

2 回答 2

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
于 2013-05-15T17:14:58.570 回答
0

我所做的是我得到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在数据库中正确插入对象,它应该可以工作)。

于 2013-05-15T16:50:32.120 回答