0

I need to Upload Image selected in the Website into the DB My project has multiple File Select "File Upload" how can I Upload those multiple Files into Database the Image data in Binary Format, My Code is

    protected void Button1_Click(object sender, EventArgs e)

   {

        string Qry = "insert into tblFiles values(@data)";
        SqlConnection con = new SqlConnection(@"Data Source=ESLHPC17\SQL2008;Initial Catalog=dbFiles;User ID=user;Password=password");

        SqlCommand cmd = new SqlCommand(Qry,con);
        cmd.Parameters.Add("@data") = FileUpload1.FileBytes;

    }

I am using the Following Web Handler to Save the Files in local Folder

<%@ WebHandler Language="C#" Class="Upload" %>

using System;
using System.Web;
using System.IO;


public class Upload : IHttpHandler {

public void ProcessRequest (HttpContext context) {
    context.Response.ContentType = "text/plain";
    context.Response.Expires = -1;
    try
    {
        HttpPostedFile postedFile = context.Request.Files["Filedata"];

        string savepath = "";
        string tempPath = "";
        tempPath = System.Configuration.ConfigurationManager.AppSettings["FolderPath"]; 
        savepath = context.Server.MapPath(tempPath);
        string filename = postedFile.FileName;
        if (!Directory.Exists(savepath))
            Directory.CreateDirectory(savepath);

        postedFile.SaveAs(savepath + @"\" + filename);
        context.Response.Write(tempPath + "/" + filename);
        context.Response.StatusCode = 200;
    }
    catch (Exception ex)
    {
        context.Response.Write("Error: " + ex.Message);
    }
}

public bool IsReusable {
    get {
        return false;
    }
}

}

and I use the below Script

 <script type = "text/javascript">
      $(window).load(
function () {
    $("#<%=FileUpload1.ClientID%>").fileUpload({
        'uploader': 'scripts/uploader.swf',
        'cancelImg': 'images/cancel.png',
        'buttonText': 'Browse Files',
        'script': 'Upload.ashx',
        'folder': 'Uploads',
        'fileDesc': 'Image Files',
        'fileExt': '*.jpg;*.jpeg;*.gif;*.png',
        'multi': true,
        'auto': false
    });

but I want to store the Images in Database


@ Damith

I have tried in with the below mentioned code but it didn't worked,

   protected void Button1_Click(object sender, EventArgs e)
    {
        string FolderPath=@"E:\Rajesh_Kumar\Application\Valuation\ExamManagement\ExamManagement\Uploads";
        string path = System.Configuration.ConfigurationManager.AppSettings[FolderPath];
        string Qry = "insert into tblFiles values(@data) Values (data)";
        SqlConnection con = new SqlConnection(@"Data Source=ESLHPC17\SQL2008;Initial Catalog=dbFiles;User ID=rajesh";
        StreamReader sr = new StreamReader(path);
        while (sr.ReadLine() != null)
        {

                using (SqlCommand cmd = new SqlCommand(Qry, con))
                {
                    cmd.Parameters.Add("@data",SqlDbType.VarBinary).Value = path;
                    con.Open();
                    cmd.ExecuteNonQuery();
                }
            con.Close();
            con.Dispose();
        }

    }
5
  • 1
    You really shouldn't be exposing your sa password. Nor should your application be logging in as the sa user. Commented May 7, 2013 at 10:59
  • Execute the command and you'll be set. What is your question? Commented May 7, 2013 at 11:07
  • @CodeCaster the problem is, that only handles a single file at the moment Commented May 7, 2013 at 11:10
  • @LukeHennerley that's nice of you, but OP should mention that, especially since all information after that is missing: in what part he's having trouble. Creating FileUpload's on the fly? Getting input from multiple FileUpload's? Reading all uploaded files from a single FileUpload? Executing multiple queries at once, or running a single insert query for multiple data? Commented May 7, 2013 at 11:12
  • @ Colin Mackay Okie Mr.Mackay thanks for your Advice... Commented May 8, 2013 at 11:03

2 Answers 2

2

try with

foreach (HttpPostedFile uploadedFile in FileUpload1.PostedFiles)
{
    SaveImage(uploadedFile);
}

private void SaveImage(HttpPostedFile file)
{
   using(SqlConnection con = new SqlConnection(ConnectionString))// set ConnectionString
   {
       using(SqlCommand cmd = new SqlCommand(Qry,con)) // set Qry
       {
          cmd.Parameters.AddWithValue("@data", ReadFile(file));
          con.Open();
          cmd.ExecuteNonQuery();
       }
   }
}

private byte[] ReadFile(HttpPostedFile file)
{
    byte[] data = new Byte[file.ContentLength];
    file.InputStream.Read(data, 0, file.ContentLength);
    return data;
}

If you need to insert images from server folder and assume you have array of image paths as imageArray then

foreach (var path in imageArray)
{
    SaveImage(path);
}

private void SaveImage(string path)
{
   using(SqlConnection con = new SqlConnection(ConnectionString))// set ConnectionString
   {
       using(SqlCommand cmd = new SqlCommand(Qry,con)) // set Qry
       {
          cmd.Parameters.AddWithValue("@data", System.IO.File.ReadAllBytes(path));
          con.Open();
          cmd.ExecuteNonQuery();
       }
   }
}
Sign up to request clarification or add additional context in comments.

5 Comments

@ Damith The File Upload1 has only Posted File not Posted Files do I need to add some References ???
.NET Framework 4.5 need for this. msdn.microsoft.com/en-us/library/…
@ Damith I have only .Net Framework 4.0 and My OS is Windows XP So it don't support .NET Framework 4.5 Is there any other way I can Access "FileUpload1.PostedFiles" like some references
then read from saved folder and insert to database one by one.
@ Damith I have tried the way You said and Mentioned the Code in the Answer Part below but that didn't worked
1
foreach(HttpPostedFile file in FileUpload1.PostedFiles)
{
  var memoryStream = new MemoryStream();
  file.InputStream.CopyTo(memoryStream);
  string Qry = "insert into tblFiles values(@data)";
        SqlConnection con = new SqlConnection(@"Data Source=ESLHPC17\SQL2008;Initial Catalog=dbFiles;User ID=user;Password=password");

        SqlCommand cmd = new SqlCommand(Qry,con);
        cmd.Parameters.Add("@data") = memoryStream.ToArray();

}

1 Comment

Query, command and connection can be initialized outside the foreach, command does not get executed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.