【发布时间】:2015-11-13 23:31:39
【问题描述】:
我想处理表单提交并将 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 数据库过程
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
我发现当我将输入流分配给内存流时,内存流是空的?!
【问题讨论】:
标签: sql-server-2008 asp.net-mvc-4