如何将选定的多个图像上传到数据库中

时间:2013-05-07 10:57:54

标签: sql-server c#-4.0

我需要将网站中选择的图像上传到数据库我的项目有多个文件选择“文件上传”如何将这些多个文件上传到数据库二进制格式的图像数据,我的代码是

    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;

    }

我正在使用以下Web处理程序将文件保存在本地文件夹

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

}

我使用下面的脚本

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

但我想将图像存储在数据库中


@ Damith

我已尝试使用下面提到的代码,但它没有用,

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

    }

2 个答案:

答案 0 :(得分:2)

尝试

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

如果您需要从服务器文件夹中插入图像并假设您有imageArray的图像路径数组,那么

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

答案 1 :(得分: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();

}