LeoStotch
LeoStotch

Reputation: 125

Saving multiple Images at once to the database with a FileUpload Control

I am working on a company Blog site, and when a user is making a post, they can add an image from their computer to the post. I used a FileUpload control to do this, and it works great. However, I am trying to change the functionality to allow the user to select and upload multiple images in one post, and I am running into some issues. I have set the 'allow multiple' property to 'true', however once multiple images are selected into the control (Image URLs get separated by a comma) and the post button is clicked, only one of the images is inserted into the database, but it is inserted as many times as images there are, and only that one image is displayed on the blog post. So if I try to add three different images, it inserts three instances of the first image into the database. The code corresponding to the the FileUpload in my onClick function is below:

  if (imageUpload.HasFile == true)
                {

                    SqlCommand maxMessId = new SqlCommand("SELECT Max(MessageID) FROM BlogMessages", conn);
                    lastMessageID = Convert.ToInt32(maxMessId.ExecuteScalar());

                    foreach (var uploadedFile in imageUpload.PostedFiles)
                    {



                        SqlCommand cmdInsertImage = new SqlCommand("INSERT INTO BlogImages(Image, MessageID) VALUES (@Image, @MessageID)", conn);

                        cmdInsertImage.Parameters.AddWithValue("@Image", SqlDbType.Image).Value = imageUpload.FileBytes;
                        cmdInsertImage.Parameters.AddWithValue("@MessageID", lastMessageID);


                        cmdInsertImage.ExecuteNonQuery();

                    }
                }

I am thinking the issue could be with:

cmdInsertImage.Parameters.AddWithValue("@Image", SqlDbType.Image).Value = imageUpload.FileBytes; 

If that is getting the file bytes for only one image.. I am not sure how to get the filebytes for both files. The image column in my BlogImages table is of the type Image.

Any suggestions are much appreciated!

Upvotes: 3

Views: 6506

Answers (3)

vaishali soni
vaishali soni

Reputation: 1

protected void btnSubmit_Click(object sender, EventArgs e) {

     string strImageName = txtImage.Text.ToString();      //to store image into sql database.



                if (FileUpload1.PostedFile != null &&
                FileUpload1.PostedFile.FileName != "")
                  {
                       byte[] imageSize = new byte[FileUpload1.PostedFile.ContentLength];
                       HttpPostedFile uploadedImage = FileUpload1.PostedFile;
                       uploadedImage.InputStream.Read(imageSize, 0, (int)FileUpload1.PostedFile.ContentLength);


                // Create SQL Command 

                SqlCommand cmd = new SqlCommand();
                cmd.CommandText = "INSERT INTO Pictures(ID,ImageName,Image)" +
                           " VALUES (@ID,@ImageName,@Image)";
                cmd.CommandType = CommandType.Text;
                cmd.Connection = conn;

                //retrieve latest ID from tables which was stored in session.
                int ID = Convert.ToInt32(System.Web.HttpContext.Current.Session["ID"].ToString());

                SqlParameter ID = new SqlParameter
                            ("@ID", SqlDbType.Int, 5);
                ID.Value = (Int32)ID;
                cmd.Parameters.Add(ID);

                SqlParameter ImageName = new SqlParameter
                            ("@ImageName", SqlDbType.VarChar, 50);
                ImageName.Value = strImageName.ToString();
                cmd.Parameters.Add(ImageName);

                SqlParameter UploadedImage = new SqlParameter("@Image", SqlDbType.Image, imageSize.Length);
                UploadedImage.Value = imageSize;
                cmd.Parameters.Add(UploadedImage);
                conn.Open();
                int result = cmd.ExecuteNonQuery();
                conn.Close();
                if (result > 0)
                    lblMessage.Text = "File Uploaded";
                lblSuccess.Text = "Successful !";


  }}

Upvotes: 0

makemoney2010
makemoney2010

Reputation: 1242

Are you sure that you're working on the right way ?????PostesFiles are the list of file and each one has it own properties you need to read from there.....nothing else

Here a simples examples

 For Each xx In fp.PostedFiles
        xx.InputStream
        xx.ContentLength
        xx.FileName


    Next

Where those properties upon expose Inputstrem a stream of the image,ContenteLenght it lenght, Filename the filename of the images.So when you pass the imageupload.FileBytes is not the correct way to achive your goal.You have to read the stream and return a bytearray to save the data withing your sql server.Nothing else i hope it could help you to solve your issue.

UPDATE*

Assume that you're into the foreach loop for each single file you have to setup its own bytearray

MemoryStream ms = new MemoryStream();
file.PostedFile.InputStream.CopyTo(ms);
var byts = ms.ToArray();
ms.Dispose();

then

change your insert statement like this

    cmdInsertImage.Parameters.AddWithValue("@Image", SqlDbType.Image).Value = byts;

not tested but it should solve the issue.

UPDATE 2

if (test.HasFiles) {

    StringBuilder sb = new StringBuilder();


    foreach (void el_loopVariable in test.PostedFiles) {
        el = el_loopVariable;
        sb.AppendLine("FILENAME:<B>" + el.FileName.ToString + "</B><BR/>");
        MemoryStream ms = new MemoryStream();
        el.InputStream.CopyTo(ms);
        byte[] byts = ms.ToArray;
        ms.Dispose();


        sb.AppendLine(string.Join(";", byts));
        sb.AppendLine("<br/<br/>");
        byts = null;
    }


    LitResponse.Text = sb.ToString;





}

Upvotes: 1

Anthony
Anthony

Reputation: 387

I think the issue is that in your for each loop, you're stepping through the posted files, but you're still just using ImageUpload.FileBytes each time, which I expect would be returning the same thing each time.

I'm not super familiar with the file upload control, but maybe you can use the ContentLength property of your uploaded file object to index into the byte array returned by ImageUpload.FileBytes (assuming that array contains each of the multiple files).

Upvotes: 0

Related Questions