2016년 12월 26일 월요일

[닷넷교육,C#교육,실무교육학원추천_탑크리에듀][예제] BLOB 이용 - 파일 업/다운 로드

[예제] BLOB 이용 - 파일 업/다운 로드 
  
  
참고 하세요~ 

<!-- http://www.codeproject.com/aspnet/upsanddowns.asp 에서 다운 받은 것 입니다. --> 
<%@ Page Language="c#" Trace="false" Debug="true" %> 
<%@ Register TagPrefix="oda" Namespace="Oracle.DataAccess" Assembly="Oracle.DataAccess, Version=9.2.0.11, Culture=neutral, PublicKeyToken=89b483f429c47342" %> 
<%@ Register TagPrefix="ic" Namespace="ICSharpCode.SharpZipLib" Assembly="ICSharpCode.SharpZipLib, Version=0.5.0.0, Culture=neutral, PublicKeyToken=1b03e6acf1164f73" %> 
<%@ Import Namespace="System.IO" %> 
<%@ Import Namespace="System.Data" %> 
<%@ Import Namespace="Oracle.DataAccess.Types" %> 
<%@ Import Namespace="Oracle.DataAccess.Client" %> 
<%@ Import Namespace="ICSharpCode.SharpZipLib.Zip" %> 
<script language="c#" runat="server"> 
        private void Page_Load(object sender, System.EventArgs e) { 
                if (!Page.IsPostBack) { 
                        // Open our database connection to the table with the BLOB field and fill our datagrid 
                        OracleConnection oConn = new OracleConnection("Data Source=MyDatabase;User ID=MyUser;Password=MyPassword"); 
                        BindDataGrid(oConn, dgdFiles, "SELECT DOC_ID AS FILE_ID, FILENAME AS FILE_NAME, DBMS_LOB.GETLENGTH(DOCUMENT) AS FILE_SIZE FROM DOCUMENT FILES"); 
                } 
        } 
        
        private void btnUpload_Click(object sender, System.EventArgs e) { 
                // If no file was uploaded then you probably want to inform the user to select a file 
                // before clicking the upload button. 
                if (filUpload.PostedFile != null) { 
                        // Get a reference to the uploaded file 
                        HttpPostedFile filPosted = filUpload.PostedFile; 
                        int intFileLength = System.Convert.ToInt32(filPosted.ContentLength); 
                        
                        // Ensure that there were contents to the file. Exit out of the function if there is no content. 
                        if (intFileLength == 0) { 
                                return; 
                        } 
                        
                        // Open our database connection to the table with the BLOB field 
                        OracleConnection oConn = new OracleConnection("Data Source=MyDatabase;User ID=MyUser;Password=MyPassword"); 
                        OracleDataAdapter oDA = new OracleDataAdapter("SELECT * FROM FILES", oConn); 
                        OracleCommandBuilder oCB = new OracleCommandBuilder(oDA); 
                        DataSet ds = new DataSet(); 
                        DataRow dr; 
                        
                        // Fill the dataset with the schema but not the data 
                        oDA.MissingSchemaAction = MissingSchemaAction.AddWithKey; 
                        oConn.Open(); 
                        oDA.FillSchema(ds, SchemaType.Source, "FILES"); 
                        
                        // This may not be necessary 
                        byte[] byteData = new byte[intFileLength]; 
                        filPosted.InputStream.Read(byteData, 0, intFileLength); 
                        
                        // Create a new row to insert into the table 
                        dr = ds.Tables["FILES"].NewRow(); 
                        dr["FILE_ID"] = 1; // this should not be needed ... it's a sequence but will not allow nulls? so the 1 is a placeholder 
                        dr["FILE_NAME"] = System.IO.Path.GetFileName(filPosted.FileName); 
                        dr["FILE_DATA"] = byteData; 
                        
                        // Append the new row to the dataset 
                        ds.Tables["FILES"].Rows.Add(dr); 
                        
                        // Update the table using our dataset against our data adapter 
                        oDA.Update(ds, "FILES"); 
                        
                        // Close our connection 
                        oConn.Close(); 
                        
                        // Refresh the contents to the datagrid 
                        BindDataGrid(oConn, dgdFiles, "SELECT DOC_ID AS FILE_ID, FILENAME AS FILE_NAME, DBMS_LOB.GETLENGTH(DOCUMENT) AS FILE_SIZE FROM DOCUMENT FILES"); 
                } 
        } 
        
        private void btnDownload_Click(object sender, System.EventArgs e) { 
                // A temp object to be used in iterating through the datagrid 
                CheckBox chkControl; 
                // will hold a comma seperated list of the IDs that were selected 
                string strIDs = ""; 
                
                // Find the checked items in the datagrid and append them to the string 
                foreach (DataGridItem dgi in dgdFiles.Items) { 
                        chkControl = (CheckBox)dgi.FindControl("chkSelection"); 
                        if (chkControl.Checked) { 
                                strIDs += ((Label)dgi.FindControl("lblFileID")).Text.ToString() + ","; 
                        } 
                } 
                
                // If there were files selected then create the ZIP file for download 
                if (strIDs.Length > 0) { 
                        // Connect to the database and grab the selected documents 
                        OracleConnection oConn = new OracleConnection("Data Source=MyDatabase;User ID=MyUser;Password=MyPassword"); 
                        OracleDataAdapter oDA = new OracleDataAdapter("SELECT FILE_NAME, FILE_DATA, DBMS_LOB.GETLENGTH(FILE_DATA) AS FILE_SIZE FROM FILES WEHRE FILE_ID IN (" + strIDs.Substring(0, strIDs.Length -1) + ")", oConn); 
                        DataSet ds = new DataSet(); 
                        
                        // Open the database connection and fill the dataset 
                        oConn.Open(); 
                        oDA.Fill(ds, "FILES"); 
                        
                        // Create the ZIP file that will be downloaded. Need to name the file something unique ... 
                        string strNow = String.Format("{0:MMM-dd-yyyy_hh-mm-ss}", System.DateTime.Now); 
                        ZipOutputStream zipOS = new ZipOutputStream(File.Create(Server.MapPath("./") + strNow + ".zip")); 
                        zipOS.SetLevel(5); // ranges 0 to 9 ... 0 = no compression : 9 = max compression 
                        
                        // Loop through the dataset to fill the zip file 
                        foreach (DataRow dr in ds.Tables["FILES"].Rows) { 
                                ZipEntry zipEntry = new ZipEntry(dr["FILE_NAME"].ToString()); 
                                zipOS.PutNextEntry(zipEntry); 
                                zipOS.Write((byte[])dr["FILE_DATA"], 0, System.Convert.ToInt32(dr["FILE_SIZE"])); 
                        } 
                        
                        // Close the database connection 
                        oConn.Close(); 
                        
                        // Compress and close the zip file 
                        zipOS.Finish(); 
                        zipOS.Close(); 
                        
                        // When the page reloads we need to redirect the user to the file 
                        string script1 = "<script language=javascript>function gotoZip() {document.location.href = '" + strNow + ".zip';}</" + "script>"; 
                        string script2 = "<script language=javascript>document.body.onload = gotoZip;</" + "script>"; 
                        Page.RegisterStartupScript("download1", script1); 
                        Page.RegisterStartupScript("download2", script2); 
                } 
        } 
        
        private void lblFileSize_DataBinding(object sender, System.EventArgs e) { 
                // Formatting the label to show the file size in kilobytes 
                Label lblSize = (Label)sender; 
                lblSize.Text = String.Format("{0:#,###}", System.Math.Ceiling(System.Convert.ToDouble(lblSize.Text) / 1024)); 
        } 
        
        private void BindDataGrid(OracleConnection o, DataGrid d, string sql) { 
                OracleCommand oComm = new OracleCommand(sql, o); 
                o.Open(); 
                d.DataSource = oComm.ExecuteReader(CommandBehavior.CloseConnection); 
                d.DataBind(); 
        } 
</script> 
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> 
<html> 
        <head> 
                <title>An Example of Uploading Files to a Database ... and Downloading in a Single Zip File</title> 
                <script language="javascript" type="text/javascript"> 
                        // a simple function to find toggle all of the checkboxes in a form 
                        function checkAll(o) { 
                                for (var i = 0; i < document.myForm.elements.length; i++) { 
                                        if (document.myForm.elements[i].type == "checkbox") { 
                                                document.myForm.elements[i].checked = o.checked; 
                                        } 
                                } 
                        } 
                </script> 
                <style> 
                        fieldset { 
                                cursor: default; 
                                font-family: Arial; 
                        } 
                        div { 
                                width: 400px; 
                        } 
                </style> 
        </head> 
        <body> 
                <form runat="server" id="myForm" name="myForm" method="post" enctype="multipart/form-data"> 
                        <div align="center"> 
                                <fieldset> 
                                        <legend>Upload Portion</legend> 
                                        <input runat="server" id="filUpload" type="file"> 
                                        <asp:Button runat="server" id="btnUpload" OnClick="btnUpload_Click" Text="Begin Upload" /> 
                                </fieldset> 
                                <fieldset> 
                                        <legend>Download Portion</legend> 
                                        <asp:DataGrid runat="server" id="dgdFiles" AutoGenerateColumns="false"> 
                                                <columns> 
                                                        <asp:TemplateColumn> 
                                                                <HeaderTemplate> 
                                                                        <input runat="server" type="checkbox" ID="chkSelectAll" title="Select All Files" onclick="checkAll(this);" /> 
                                                                </HeaderTemplate> 
                                                                <ItemTemplate> 
                                                                        <asp:Checkbox ID="chkSelection" runat="server" /> 
                                                                        <asp:Label ID="lblFileID" Visible="false" Text='<%# DataBinder.Eval(Container.DataItem, "FILE_ID") %>' runat="server" /> 
                                                                </ItemTemplate> 
                                                        </asp:TemplateColumn> 
                                                        <asp:TemplateColumn HeaderText="File Name"> 
                                                                <ItemTemplate> 
                                                                        <asp:Label ID="lblFileName" Text='<%# DataBinder.Eval(Container.DataItem, "FILE_NAME") %>' runat="server" /> 
                                                                </ItemTemplate> 
                                                        </asp:TemplateColumn> 
                                                        <asp:TemplateColumn HeaderText="File Size"> 
                                                                <ItemStyle HorizontalAlign="right" /> 
                                                                <ItemTemplate> 
                                                                        <asp:Label ID="lblFileSize" Text='<%# DataBinder.Eval(Container.DataItem, "FILE_SIZE") %>' runat="server" OnDataBinding="lblFileSize_DataBinding" /> 
                                                                        <asp:Label ID="lblKB" Text=" kb" runat="server" /> 
                                                                </ItemTemplate> 
                                                        </asp:TemplateColumn> 
                                                </columns> 
                                        </asp:DataGrid> 
                                        <asp:Button runat="server" id="btnDownload" OnClick="btnDownload_Click" Text="Zip and Download" /> 
                                </fieldset> 
                        </div> 
                </form> 
        </body> 
</html> 
  

댓글 없음:

댓글 쓰기