unable to upload multiple db images with asp.net m

2020-03-29 08:20发布

问题:

I am trying to upload several db images onto the SQL Server 2008R2. I am using ASP.NET MVC 3 in C#. What is happening is that I getting the images displayed but the problem is that the second image is being displayed as twice. So it is duplicate. I am not sure why the first image is not being displayed.

My SubProductCategory4 Table has the following columns (for simplicity sake)...

Column Names: Image1 and Image2 has DataTypes varbinary(MAX), another column Name: ImageMimeType has DataTypes varchar(50).

My Controller has the following code for Create method...

[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);
    } 

GetImage method...

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;
    }

}

create.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>

index.cshtml...

<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>

I am using using VS2010, ASP.NET MVC3 in C# with SQL Server 2008R2. Thanks in advance but please only respond if you know the answer. If there is a better way of doing this please let me know.

回答1:

The code that is listed is looping through the files, and for each one, setting both Image1 and Image2 to be the same thing. When you upload 2 files, they are both showing up as image 2 because that was the last image applied to both fields.

Try replacing the loop with something more like this, which sets the fields one at a time if there are enough images.

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);

If you need to open this up to allow more images in the future, you'll want to replace the Image1 and Image2 fields with a collection of images, and use your loop again to add each image in the uploaded files collection. Something like this:

FileHandler fh = new FileHandler();

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

db.AddToSubProductCategory4(Createsubcat4);
db.SaveChanges();

EDIT:

Now that you are saving the images correctly, you need to take a second look at your GetImage action. You'll notice that you correctly load both files into memory, however when you specify your action result (return new FileStreamResult(stream,"image/jpg");) you are only ever returning the first stream. You need a way to return the second stream when requested. There are a couple ways to go about this, add another input parameter to specify which image to load or create a second action that only returns the second one.

To create the two action set up, your code would look something like this:

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");
}

These functions are almost identical and can easily be made 1 which takes a parameter to select which image to load.

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");
}

This function would specify the imageNum as a query parameter like:

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



回答2:

I think your problem might be in this loop.

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);

The Request.Files.Count > 0 should always be true since you are iterating through a list of Files. However, the real issue is that with this loop you overwrite the properties of Createsubcat4 with each file, and then after the properties are set with the last file, that is what gets sent to the database.

If you are trying to add multiple records into the database (one for each image), you'll need to move the AddToSubProductCategory4 within the loop. If you are trying to add two images to just that record, I'd recommend assigning each by name, and skipping the foreach loop.