将图像数据保存到文件,同时还更新数据库

时间:2012-09-19 10:31:25

标签: c# asp.net image binary

我正在尝试将图像作为varbinary数据类型上传到我的数据库中。

问题是我还想将来自字节数组的图像数据存储到我的解决方案中名为TextFile.txt的文件中。但我无法这样做。 我希望它在将图像插入数据库的同时写入数据。

我有这个代码,我可以将图像插入到数据库中,但不能将字节数据插入到文本文件中。

protected void Button1_Click(object sender, EventArgs e)   
{
    if (!this.FUImage.HasFile)
    {
        this.Label1.Text = "Please select a file to Uplaod";
        return;
    }

    MemoryStream ms = new MemoryStream();
    this.FUImage.PostedFile.InputStream.CopyTo(ms);
    var bytes = ms.ToArray();
    ms.Close();
    var image = new Image() {
        Name = this.FUImage.PostedFile.FileName,
        FileBinary = bytes
    };
    SaveImageData(image);
}

3 个答案:

答案 0 :(得分:0)

方法SaveImageData有什么作用?你在这里试图提交文件吗?

http://social.msdn.microsoft.com/Forums/en/csharpgeneral/thread/005f0060-09c1-4ba9-8a40-cc7fa7284320

答案 1 :(得分:0)

使用二进制写入器写入字节数据。

MemoryStream ms = new MemoryStream();  
        this.FUImage.PostedFile.InputStream.CopyTo(ms);   
        var bytes = ms.ToArray();   
        ms.Close();   
        var image = new Image()   
        {   
            Name = this.FUImage.PostedFile.FileName,   
            FileBinary = bytes   
        };  



 using (FileStream fs = new FileStream(FILE_NAME, FileMode.CreateNew))  
        {
            using (BinaryWriter w = new BinaryWriter(fs))  
            {  
                for (int i = 0; i < 11; i++)  
                {  
                    w.Write(bytes);  

                }  
            }  
        }  

答案 2 :(得分:0)

您应首先使用byte方法将base64String数组转换为Convert.ToBase64String Method (Byte[]),然后将字符串写入任何文本文件。

var bytes = ms.ToArray();
string imageString = Convert.ToBase64String Method ();
System.IO.File.WriteAllText (@"D:\path.txt", imageString );