简体   繁体   中英

Select multiple image files using fileupload control(ASP.net C#) and save it in database in one click.

I am able to select multiple files using fileupload control but when I try to save it to a database it's giving me an "Object reference not set to an instance of an object" error.

if (FileUpload1.HasFiles)
{
     foreach (HttpPostedFile uploaded in FileUpload1.PostedFiles)
     {
         bindata = new BinaryReader(uploaded.InputStream);
         ImageByteArray = bindata.ReadBytes(uploaded.ContentLength);

         // byte array is sent to a method
         dbmt.SaveImageToDB(ImageByteArray);
     }
}

And the following is my code for the SaveImageToDB method

public void SaveImageToDB(byte[] ImageByteArray)
{
    try
    {
        scon.Open();
        scm.Connection = scon;

        scm.CommandType = CommandType.StoredProcedure;
        scm.CommandText = "SaveProfileImage";

        SqlParameter paramImgArray = scm.Parameters.Add("@ImgBody", SqlDbType.Image,0);
        paramImgArray.Direction = ParameterDirection.Input;
        paramImgArray.Value = ImageByteArray;

        scm.ExecuteNonQuery();
    }
    catch( SqlException sqx )
    {
        throw sqx;
    }
}

Set The Property AllowMultiple = True in fileupload control.

protected void uploadFile_Click(object sender, EventArgs e)
{
   if (UploadImages.HasFiles)
   {
       foreach (HttpPostedFile uploadedFile in UploadImages.PostedFiles)
       {
           uploadedFile.SaveAs(System.IO.Path.Combine(Server.MapPath("~/Images/"),
           uploadedFile.FileName));
           listofuploadedfiles.Text += String.Format("{0}<br/>", uploadedFile.FileName);
       }
   }

}

I understand that it is giving an error in the said method, but on which line inside that method is giving this error?

I assume that the method you have given here is complete (ie there is no code which you have deleted before pasting it here), so i guess there are only 2 objects which could be null and those are "scon" and "scm". Put a breakpoint on the line "scon.Open();" and on line "scm.Connection = scon;". Once the execution stops on each of these lines, hover your mouse over "scon" and then over "scm". I guess either one of them will be null.

Hope this helps.

The problem was my object. It was not instantiated correctly. I was accessing a class within appcode called DBmiddleTier to access a database and write the image file. Here is what I did wrong: DBMiddleTier dbmt; <-----"WRONG". Here is what I did to correct the problem DBMiddleTier dbmt = new DBMiddleTier();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM