如何将上传的图像插入varbinary(max)数据库列

时间:2015-11-13 12:54:27

标签: sql-server-2008 asp.net-mvc-4

我希望流程表单提交并将jpg图像保存到varbinary sql列中。 我有代码,但它无法正常工作,它只保存像0x00...0000这样的空字节。因此,不会引发错误并成功插入数据库行,但varbinary列似乎已损坏。

代码如下

模型

public class FrontendModel
    {
        public HttpPostedFileBase Photo1 { get; set; }
    }

public class SubmitModel
    {
        public byte[] ImageData { get; set; }
        public decimal ImageSizeB { get; set; }

        public SubmitModel
        (
            HttpPostedFileBase Photo
        )
        {

            this.ImageData = new byte[Photo.ContentLength];
            Photo.InputStream.Read(ImageData, 0, Convert.ToInt32(Photo.ContentLength));

        this.ImageSizeB = Photo.ContentLength;
    }

控制器

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Index(FrontendModel m)
{

    using (var db = new ABC.Models.ABCDBContext())
    {

        using (var scope = new TransactionScope())
        {
            if (m.Photo1 != null && m.Photo1.ContentLength > 0)
                db.InsertSubmit(new SubmitModel(m.Photo1));

            scope.Complete();
        }
    }

    return View(new FrontendModel());
}

数据库插入功能

public void InsertSubmit(SubmitModel m)
{
    Database.ExecuteSqlCommand(
        "spInsertSubmit @p1",
        new SqlParameter("p1", m.ImageData),
    );
}

SQL DB程序

CREATE PROCEDURE [dbo].[spInsertSubmit]
    @ImageData VARBINARY(max)
AS
        INSERT INTO dbo.Images (Image)
        VALUES (@ImageData)
我做错了什么?谢谢

PS:

我也试过这样的东西,但行为相同

using (var binaryReader = new BinaryReader(Photo.InputStream))
            {
                this.ImageData = binaryReader.ReadBytes(Photo.ContentLength);
            }

然后我试了

using (Stream inputStream = Photo.InputStream)
            {
                MemoryStream memoryStream = inputStream as MemoryStream;
                if (memoryStream == null)
                {
                    memoryStream = new MemoryStream();
                    inputStream.CopyTo(memoryStream);
                }
                ImageData = memoryStream.ToArray();
            }

但在调用DB函数时出现错误,错误消息为Parameter is not valid

我遇到的问题与此处提到的相同 File uploading and saving to database incorrectly

enter image description here

我发现当我将输入流分配给内存流时,内存流是空的?!

2 个答案:

答案 0 :(得分:1)

您的过程指定该参数名为@ImageData,但您的代码为

  Database.ExecuteSqlCommand(
        "spInsertSubmit @p1",
        new SqlParameter("p1", m.ImageData),
    );

似乎传递了一个名为@ p1

的参数

修改

另外我认为在处理大于8k的字节数组时必须明确指定类型。请看这个链接:Inserting a byte array larger than 8k bytes

 Database.ExecuteSqlCommand(
        "spInsertSubmit @p1",
        new SqlParameter("@p1", SqlDbType.VarBinary) { Value = m.ImageData },
    );

答案 1 :(得分:0)

好的,我找到了解决方案。这段代码有效!

this.ImageData = new byte[streamLength];
Photo.InputStream.Position = 0;
Photo.InputStream.Read(this.ImageData, 0, this.ImageData.Length);

添加的行是 Photo.InputStream.Position = 0;