2013-05-07 2 views
0

웹 사이트에서 선택한 이미지를 DB에 업로드해야합니다. 내 프로젝트에 여러 개의 파일 선택 "파일 ​​업로드"가 있습니다. 여러 파일을 이진 형식으로 이미지 데이터를 데이터베이스에 업로드하려면 어떻게해야합니까? 내 코드는 내가 로컬 폴더선택한 여러 이미지를 데이터베이스에 업로드하는 방법

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

}

에 파일을 저장하려면 다음 웹 처리기를 사용하고

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; 

    } 

내가 SCRI 아래를 사용 PT

<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 [email protected]"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(); 
     } 

    } 
+1

당신은 정말 당신의'sa' 비밀번호를 노출 할 수 없습니다. 또한 응용 프로그램이'sa' 사용자로 로그인하지 않아야합니다. –

+0

명령을 실행하면 설정됩니다. 귀하의 질문은 무엇인가? – CodeCaster

+0

@CodeCaster 문제는 그저 하나의 파일 만 처리한다는 것입니다. – LukeHennerley

답변

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

@ Damith 파일 Upload1에는 게시 된 파일 만 게시 됨 파일은 일부 참조를 추가해야합니까? – Rajesh

+0

.NET Framework 4.5에는이 작업이 필요합니다. http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.fileupload.postedfiles.aspx – Damith

+0

@ Damith 전 .NET Framework 4.0 만 있고 내 OS는 Windows XP입니다. .NET Framework 4.5를 지원합니다. 다른 참조 할 수있는 다른 방법이 있습니까? 예를 들어 – Rajesh

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

질의, 명령 및 연결은'foreach' 외부에서 초기화 될 수 있습니다. 명령이 실행되지 않습니다. – CodeCaster

관련 문제