【问题标题】:insert an image into a database c#将图像插入数据库c#
【发布时间】:2013-05-10 08:31:37
【问题描述】:

所以我有这个代码:

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

【问题讨论】:

  • 代码似乎是正确的。你确定10000字节就够了吗?我试过了,效果很好。我的小测试图片必须将字节数提高到 400 000。
  • 考虑在数据库中存储对文件的文件名引用,并将实际文件存储在其他地方。
  • 我的图像实际上只有 60 字节大,当我试图只说 byte [] raw 然后几个留置权后来使用 raw 时,它只是跳过了 raw。所以这就是为什么我给它一个大小并提前实例化它
  • 还有一个类似的问题可能对stackoverflow.com/questions/8880213/…有帮助
  • 有什么理由不能使用var raw = System.File.IO.ReadAllBytes(uplImage.PostedFile.FileName) ?

标签: c# sql image blob


【解决方案1】:

您可以将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

【讨论】:

  • 无论出于何种原因,使用此示例都有效。不是我只需要从 varchar 转换为 varbinary,因为我的存储过程不喜欢隐式转换
【解决方案2】:

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

【讨论】:

  • 另请注意 FileStream 是 IDisposable,因此您可能希望将其丢弃或放入 using 块中。
  • 这仍然给我同样的问题。使用提供的答案中的代码,数据的大小保持为 0,没有写入任何内容。
猜你喜欢
  • 2017-05-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-09
  • 1970-01-01
相关资源
最近更新 更多