2

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.

BenMorel
  • 34,448
  • 50
  • 182
  • 322
DiscoDude
  • 617
  • 3
  • 17
  • 39

3 Answers3

4

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}

Nick Larsen
  • 18,631
  • 6
  • 67
  • 96
  • @NickLarsen - I am afraid that too did not solve the problem. The code you have provided, first images is being displayed as twice. So it is duplicate. – DiscoDude Apr 27 '11 at 15:05
  • @DiscoDude: So now you are saving the pictures correctly, and your `GetImage` action needs to be updated. Updating my response to help you more. – Nick Larsen Apr 27 '11 at 15:21
  • @NickLarsen - could you claify regarding the foreach loop... Createsubcat4.Images.Add(fh.uploadedFileToByteArray(uploadedImage));Where is this Images coming from...is that data field from the database column? Because I am getting this error message..."does not contain a definition for 'Images' and no extension method 'Images' accepting a first argument of type could be found (are you missing a using directive or an assembly reference?)" – DiscoDude Apr 27 '11 at 15:51
  • @NickLarsen: Also without foreach loop, I getting the following error message...The parameters dictionary contains a null entry for parameter 'imageNum' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.FileResult GetImage(Int32, Int32)' in 'MyApplication1.Server.ProductCategoryL4Controller'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter. Parameter name: parameters – DiscoDude Apr 27 '11 at 15:58
  • @DiscoDude: `Createsubcat4.Images.Add(fh.uploadedFileToByteArray(uploadedImage));`was only for if you need more images, my text explains how you should add an images collection property if you ever need more than 2 images. You don't have that property right now, so don't use that code, but do read the text of what I wrote, don't just copy/paste all the code. – Nick Larsen Apr 27 '11 at 16:04
  • @DiscoDude: change the `int imageNum` parameter to be nullable (`int? imageNum` and add a null check for it to the function. Also if you use the second version, make sure you specify the `imageNum` parameter as I show at the very bottom of my response. – Nick Larsen Apr 27 '11 at 16:07
  • @NickLarsen: Where is the imageNum parameter (I know you said not just copy and paste, read the text. I have done so). Also I am recieving alternativePicturePath (question_mark.jpg). When I am creating new record? Instead of the two images. – DiscoDude Apr 27 '11 at 16:17
  • @DiscoDude: That's because you are not specifying the `imageNum` parameter in your image url. Can you show me what the image url is when you right click and view source in browser? – Nick Larsen Apr 27 '11 at 16:52
  • @DiscoDude: that is exactly what I mean, you need to augment it to include the `imageNum` parameter. `localhost:****/ProductCategoryL4/GetImage/86?imageNum=1` should load image 1 and `localhost:****/ProductCategoryL4/GetImage/86?imageNum=2` should load image 2. – Nick Larsen Apr 27 '11 at 17:32
  • When I right click image url & copy to new browse the url does not include the ?imageNum={imageNum}. In other words http://localhost:7048/ProductCategoryL4/GetImage/86?imageNum={imageNum} – DiscoDude Apr 27 '11 at 17:39
  • @DiscoDude: so make that change in your view code so you are serving up the imageNum to the browser :) – Nick Larsen Apr 27 '11 at 17:43
  • Yes the images are now loading when copying the image url. So the function on the second version, shouldn't image1 & image2 get loaded correctly? I do not understand what you mean by "change in your view code so you are serving up the imageNum to the browser" – DiscoDude Apr 27 '11 at 17:47
  • @DiscoDude: So the images are loading correctly now? What's the problem? – Nick Larsen Apr 27 '11 at 17:58
  • Not quite. When creating a new record. I get question_mark.jpg images for Image1 and Image2. When it should show actual images selected. Also my Image Url I have manually type imageNum=1 at the end of localhost:****/ProductCategoryL4/GetImage/86. I have edit my code at the top to incude Create.cshtml – DiscoDude Apr 27 '11 at 18:32
  • @DiscoDude: when you edit the post, can you please also update all the code in your post to show where you are right now? – Nick Larsen Apr 27 '11 at 18:37
  • Yes I will do in future. I didn't realize cshtml were needed to amending as well. – DiscoDude Apr 27 '11 at 18:40
  • @DiscoDude: yes, you need to make 1 more change to your image url generation. Add the `imageNum` parameter to it, `Url.Action("GetImage", "ProductCategoryL4", new { id = item.SubProductCategoryFourID, imageNum = 1 })` for the first one and `Url.Action("GetImage", "ProductCategoryL4", new { id = item.SubProductCategoryFourID, imageNum = 2 })` for the second one. – Nick Larsen Apr 28 '11 at 14:30
  • 1
    Now the images are displaying as it should. Now I hope I can work on uploading several db images. I had no chance of knowing from the code you have provided, so thank you very much. Have a pint of beer of my behalf. Sending the points your way. I hope this tread will be useful to anyone else out there – DiscoDude Apr 28 '11 at 14:52
  • @NickLarsen - could you tell me what and why are ? used for public ActionResult GetImage(int id, int? imageNum) method – DiscoDude Jun 17 '11 at 17:19
0

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.

ckal
  • 3,540
  • 1
  • 22
  • 21
  • I did moved the AddToSubProductCategory4 within the loop before posting this question but I am afraid it not solve the problem. I added some comments on the code. Also changed Request.Files.Count > 0 to 1 and that too did not solve the problem. Anything other suggestions? – DiscoDude Apr 27 '11 at 14:13
  • @NickLarsen - could you tell me what and why are ? used for public ActionResult GetImage(int id, int? imageNum) method. – DiscoDude Jun 17 '11 at 17:17
  • @DiscoDude: it makes them nullable ints so that you have some indication when the parameter is not specified. Otherwise it would default to 0 every time, leaving you with an ambiguous case when the user specified that imageNum is 0. – Nick Larsen Jun 20 '11 at 21:19
0
 public JsonResult Update(ProductViewModel model, HttpPostedFileBase imgpath1, IEnumerable<HttpPostedFileBase> imgpath2)
    {
        if (imgpath1 != null)
        {
           foreach (HttpPostedFileBase postedFile in imgpath1)
            {
                //  var prodimage = Request.Files[i];
               
            }
          
        }


     
        if (imgpath2 != null)
        {
            foreach (HttpPostedFileBase postedFile in imgpath2)
            {
                 var prodimage = Request.Files[i];
               
            }

        }
 }