C# 无法使用asp.net mvc上载多个db映像

C# 无法使用asp.net mvc上载多个db映像,c#,asp.net-mvc-3,C#,Asp.net Mvc 3,我正在尝试将几个db映像上载到SQL Server 2008R2。我正在C#中使用ASP.NET MVC 3。所发生的是,我得到的图像显示,但问题是,第二个图像显示两次。所以它是重复的。我不知道为什么第一个图像没有显示 我的SubductCategory4表有以下列(为了简单起见) 列名:Image1和Image2的数据类型为varbinary(MAX),另一个列名:ImageMimeType的数据类型为varchar(50) 我的控制器具有以下创建方法的代码 [HttpPost] pu

我正在尝试将几个db映像上载到SQL Server 2008R2。我正在C#中使用ASP.NET MVC 3。所发生的是,我得到的图像显示,但问题是,第二个图像显示两次。所以它是重复的。我不知道为什么第一个图像没有显示

我的SubductCategory4表有以下列(为了简单起见)

列名:Image1和Image2的数据类型为varbinary(MAX),另一个列名:ImageMimeType的数据类型为varchar(50)

我的控制器具有以下创建方法的代码

[HttpPost]
    public ActionResult Create([Bind(Exclude = "SubProductCategoryFourID")] SubProductCategory4 Createsubcat4, IEnumerable<HttpPostedFileBase> files, FormCollection collection)
    {
        if (ModelState.IsValid)
        {
           foreach (string inputTagName in Request.Files)
           {

     if (Request.Files.Count > 0) // tried Files.Count > 1 did 
                                          // not solve the problem
                    {
                        Createsubcat4.Image1 = (new FileHandler()).uploadedFileToByteArray((HttpPostedFileBase)Request.Files[inputTagName]);
                        Createsubcat4.Image2 = (new FileHandler()).uploadedFileToByteArray((HttpPostedFileBase)Request.Files[inputTagName]);
                        // var fileName = Path.GetFileName(inputTagName);
                        //var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
                    }
                    // moved db.AddToSubProductCategory4(Createsubcat4);
                    // here  but did not solve the problem
           }
            db.AddToSubProductCategory4(Createsubcat4);
            db.SaveChanges();
            return RedirectToAction("/");
        }


   //someother code

        return View(Createsubcat4);
    } 
public FileResult GetImage(int id)
    {
        const string alternativePicturePath = @"/Content/question_mark.jpg";
        MemoryStream stream;
        MemoryStream streaml;

        SubProductCategory4 z = db.SubProductCategory4.Where(k => k.SubProductCategoryFourID == id).FirstOrDefault();

        if ((z != null && z.Image1 != null) && (z != null && z.Image2 != null))
        {

                stream = new MemoryStream(z.Image1);
                streaml = new MemoryStream(z.Image2);
        }

        else
        {
              var path = Server.MapPath(alternativePicturePath);

             foreach (byte item in Request.Files)
              { 
                HttpPostedFileBase file = Request.Files[item];
                if (file.ContentLength == 0)
                {
                    continue;
                }
             }

            stream = new MemoryStream();
            var imagex = new System.Drawing.Bitmap(path);
            imagex.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
            stream.Seek(0, SeekOrigin.Begin);

           /* streaml = new MemoryStream();
            var imagey = new System.Drawing.Bitmap(path);
            imagey.Save(streaml, System.Drawing.Imaging.ImageFormat.Jpeg);
            streaml.Seek(0, SeekOrigin.Begin);*/
        }

       return new FileStreamResult(stream,"image/jpg");

    }
FileHandler.cs

public class FileHandler
{
    public byte[] uploadedFileToByteArray(HttpPostedFileBase file)
    {
        int nFileLen = file.ContentLength;
        byte[] result = new byte[nFileLen];

        file.InputStream.Read(result, 0, nFileLen);

        return result;
    }

}
创建.cshtml

     @using (Html.BeginForm("Create", "ProductCategoryL4", "GetImage",  
     FormMethod.Post, new { enctype = "multipart/form-data" }))    
      //some code then...
     <div class="editor-field">
     @Html.EditorFor(model => model.Image1)
    <input type="file" id="fileUpload1" name="fileUpload1" size="23"/>
     @Html.ValidationMessageFor(model => model.Image1)
    </div>

     <div class="editor-field">
     @Html.EditorFor(model => model.Image2)
     <input type="file" id="fileUpload2" name="fileUpload2" size="23"/>
     @Html.ValidationMessageFor(model => model.Image2)
    </div>
<img src="@Url.Action("GetImage", "ProductCategoryL4", new { id =   
item.SubProductCategoryFourID })" alt="" height="100" width="100" /> 
</td>
  <td>
    <img src="@Url.Action("GetImage", "ProductCategoryL4", new { id = 
    item.SubProductCategoryFourID })" alt="" height="100" width="100" /> 
  </td>
@使用(Html.BeginForm(“创建”、“ProductCategoryL4”、“GetImage”,
FormMethod.Post,新的{enctype=“multipart/form data”})
//一些代码然后。。。
@EditorFor(model=>model.Image1)
@Html.ValidationMessageFor(model=>model.Image1)
@EditorFor(model=>model.Image2)
@Html.ValidationMessageFor(model=>model.Image2)
cshtml

     @using (Html.BeginForm("Create", "ProductCategoryL4", "GetImage",  
     FormMethod.Post, new { enctype = "multipart/form-data" }))    
      //some code then...
     <div class="editor-field">
     @Html.EditorFor(model => model.Image1)
    <input type="file" id="fileUpload1" name="fileUpload1" size="23"/>
     @Html.ValidationMessageFor(model => model.Image1)
    </div>

     <div class="editor-field">
     @Html.EditorFor(model => model.Image2)
     <input type="file" id="fileUpload2" name="fileUpload2" size="23"/>
     @Html.ValidationMessageFor(model => model.Image2)
    </div>
<img src="@Url.Action("GetImage", "ProductCategoryL4", new { id =   
item.SubProductCategoryFourID })" alt="" height="100" width="100" /> 
</td>
  <td>
    <img src="@Url.Action("GetImage", "ProductCategoryL4", new { id = 
    item.SubProductCategoryFourID })" alt="" height="100" width="100" /> 
  </td>


我正在使用VS2010,ASP.NETMVC3和SQLServer2008R2。提前感谢,但请仅在知道答案的情况下回复。如果有更好的方法,请告诉我

我想你的问题可能在这个循环中

foreach (string inputTagName in Request.Files)
{
    if (Request.Files.Count > 0)
    {
        Createsubcat4.Image1 = (new FileHandler()).uploadedFileToByteArray((HttpPostedFileBase)Request.Files[inputTagName]);
        Createsubcat4.Image2 = (new FileHandler()).uploadedFileToByteArray((HttpPostedFileBase)Request.Files[inputTagName]);
        // var fileName = Path.GetFileName(inputTagName);
        //var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
     }
}
db.AddToSubProductCategory4(Createsubcat4);
Request.Files.Count>0
应该始终为真,因为您正在迭代文件列表。但是,真正的问题是,通过此循环,您将使用每个文件覆盖Createsubcat4的属性,然后在使用最后一个文件设置属性之后,这就是发送到数据库的内容


如果试图向数据库中添加多条记录(每个图像一条记录),则需要在循环中移动addToSubProductCategory 4。如果您正试图向该记录添加两个图像,我建议按名称分配每个图像,并跳过foreach循环。

列出的代码在文件中循环,对于每个文件,将
Image1
Image2
设置为相同的内容。上载2个文件时,它们都显示为图像2,因为这是应用于这两个字段的最后一个图像

尝试用类似的方法替换循环,如果有足够的图像,可以一次设置一个字段

FileHandler fh = new FileHandler();

if (Request.Files.Count > 0)
{
    Createsubcat4.Image1 = fh.uploadedFileToByteArray(Request.Files[0]);
}

if (Request.Files.Count > 1)
{
    Createsubcat4.Image2 = fh.uploadedFileToByteArray(Request.Files[1]);
}

db.AddToSubProductCategory4(Createsubcat4);
如果需要打开此窗口以允许将来使用更多图像,则需要将
Image1
Image2
字段替换为图像集合,然后再次使用循环将每个图像添加到上载的文件集合中。大概是这样的:

FileHandler fh = new FileHandler();

foreach (HttpPostedFileBase uploadedImage in Request.Files)
{
    Createsubcat4.Images.Add(fh.uploadedFileToByteArray(uploadedImage));
}

db.AddToSubProductCategory4(Createsubcat4);
db.SaveChanges();
public ActionResult GetImage1(int id)
{
    const string alternativePicturePath = @"/Content/question_mark.jpg";
    MemoryStream stream;

    SubProductCategory4 z = db.SubProductCategory4.Where(k => k.SubProductCategoryFourID == id).FirstOrDefault();

    if (z != null && z.Image1 != null)
    {
        stream = new MemoryStream(z.Image1);
    }
    else
    {
        var path = Server.MapPath(alternativePicturePath);

        stream = new MemoryStream();
        var imagex = new System.Drawing.Bitmap(path);
        imagex.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
        stream.Seek(0, SeekOrigin.Begin);
    }

    return new FileStreamResult(stream,"image/jpg");
}

public ActionResult GetImage2(int id)
{
    const string alternativePicturePath = @"/Content/question_mark.jpg";
    MemoryStream stream;

    SubProductCategory4 z = db.SubProductCategory4.Where(k => k.SubProductCategoryFourID == id).FirstOrDefault();

    if (z != null && z.Image2 != null) // the difference is here
    {
        stream = new MemoryStream(z.Image2); // the difference is also here
    }
    else
    {
        var path = Server.MapPath(alternativePicturePath);

        stream = new MemoryStream();
        var imagex = new System.Drawing.Bitmap(path);
        imagex.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
        stream.Seek(0, SeekOrigin.Begin);
    }

    return new FileStreamResult(stream,"image/jpg");
}

编辑:

现在您已经正确保存了图像,您需要再次查看
GetImage
操作。您会注意到,您已正确地将这两个文件加载到内存中,但是,当您指定操作结果(
返回新文件streamresult(stream,“image/jpg”);
)时,您只能返回第一个流。您需要一种在请求时返回第二个流的方法。有两种方法可以实现这一点,添加另一个输入参数以指定要加载的图像或创建只返回第二个操作的第二个操作

要创建两个动作设置,代码如下所示:

FileHandler fh = new FileHandler();

foreach (HttpPostedFileBase uploadedImage in Request.Files)
{
    Createsubcat4.Images.Add(fh.uploadedFileToByteArray(uploadedImage));
}

db.AddToSubProductCategory4(Createsubcat4);
db.SaveChanges();
public ActionResult GetImage1(int id)
{
    const string alternativePicturePath = @"/Content/question_mark.jpg";
    MemoryStream stream;

    SubProductCategory4 z = db.SubProductCategory4.Where(k => k.SubProductCategoryFourID == id).FirstOrDefault();

    if (z != null && z.Image1 != null)
    {
        stream = new MemoryStream(z.Image1);
    }
    else
    {
        var path = Server.MapPath(alternativePicturePath);

        stream = new MemoryStream();
        var imagex = new System.Drawing.Bitmap(path);
        imagex.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
        stream.Seek(0, SeekOrigin.Begin);
    }

    return new FileStreamResult(stream,"image/jpg");
}

public ActionResult GetImage2(int id)
{
    const string alternativePicturePath = @"/Content/question_mark.jpg";
    MemoryStream stream;

    SubProductCategory4 z = db.SubProductCategory4.Where(k => k.SubProductCategoryFourID == id).FirstOrDefault();

    if (z != null && z.Image2 != null) // the difference is here
    {
        stream = new MemoryStream(z.Image2); // the difference is also here
    }
    else
    {
        var path = Server.MapPath(alternativePicturePath);

        stream = new MemoryStream();
        var imagex = new System.Drawing.Bitmap(path);
        imagex.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
        stream.Seek(0, SeekOrigin.Begin);
    }

    return new FileStreamResult(stream,"image/jpg");
}
这些函数几乎完全相同,可以很容易地设置为1,它使用一个参数来选择要加载的图像

public ActionResult GetImage(int id, int? imageNum)
{
    imageNum = imageNum ?? 0;

    const string alternativePicturePath = @"/Content/question_mark.jpg";
    MemoryStream stream;

    SubProductCategory4 z = db.SubProductCategory4.Where(k => k.SubProductCategoryFourID == id).FirstOrDefault();

    byte[] imageData = null;

    if (z != null)
    {
        imageData = imageNum == 1 ? z.Image1 : imageNum == 2 ? z.Image2 : null;
    }

    if (imageData != null)
    {
        stream = new MemoryStream(imageData);
    }
    else
    {
        var path = Server.MapPath(alternativePicturePath);

        stream = new MemoryStream();
        var imagex = new System.Drawing.Bitmap(path);
        imagex.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
        stream.Seek(0, SeekOrigin.Begin);
    }

    return new FileStreamResult(stream,"image/jpg");
}
此函数将指定
imageNum
作为查询参数,如下所示:


http://www.mydomain.com/controllerName/GetImage/{id}?imageNum={imageNum}

在发布此问题之前,我确实在循环中移动了AddToSubProductCategory4,但我担心它无法解决问题。我对代码添加了一些注释。还将Request.Files.Count>0更改为1,这也没有解决问题。还有其他建议吗?@NickLarsen-你能告诉我你的建议是什么以及为什么吗?用于public ActionResult GetImage(int-id,int?imageNum)方法。@DiscoDude:它使它们成为可为null的int,以便在未指定参数时有一些指示。否则每次都会默认为0,当用户指定imageNum为0时,会给您留下一个不明确的情况。@NickLarsen-恐怕这也不能解决问题。根据您提供的代码,第一个图像将显示两次。所以它是重复的。@DiscoDude:所以现在您正确地保存了图片,并且您的
GetImage
操作需要更新。更新我的回复以帮助您更多。@NickLarsen-您能澄清关于foreach循环的问题吗。。。Createsubcat4.Images.Add(fh.uploadedFileToByteArray(uploadedImage));这些图像来自何处…数据字段来自数据库列吗?因为我收到此错误消息…”不包含“Images”的定义,并且找不到接受类型为的第一个参数的扩展方法“Images”(是否缺少using指令或程序集引用?)“@NickLarsen:也没有foreach循环,我收到以下错误消息…参数字典包含“MyApplication1.Server.ProductCategory4Controller”中“System.Int32”方法“System.Web.Mvc.FileResult GetImage(Int32,Int32)”的非null类型的参数“imageNum”的null条目。可选参数必须是引用类型、可为null的类型或声明为可选参数。参数名称:参数图像按应有方式显示。现在我希望我可以上传几张db图片。我没有机会从你提供的代码中知道,所以非常感谢你。替我喝一品脱啤酒。按你的方式发送积分。我希望这一步对其他人有用