How handling Upload file module in Asp.Net

June 30, 2007

I would like to share about how to handling the upload file or creating something in your project which is need for file uploading, in this part there are some purpose that we want to achieve :

1. Browsing the file in local client into the list of file uploading

2. Move the all file list into the table which already to sent to web server  

  • The UI design                          * User Control for Editing and viewing Files

           UI Design                   grid-view-file.jpg

  • From the UI design I made the MediaFileUpload.Aspx , and then in the code behind of this control you need to made a declaration for web file repository like this : 

string webRepository=((stringSystem.Configuration.ConfigurationSettings.AppSettings.Get(“WebDataRequestRepository”));     

  • Next you need to create the method which has purpose to handling file uploading in this case we call it public void Upload_ServerClick(), but before that you must using the System.IO for IO accesing into the web file repository.
  • Beside those method above, i have made another method for define the file type validation for the user which is the bussiness process required only certain file type that should be updated into the system which return the string for file name type, in this case we call the TypeFile().
  • And the last of method for saving the file we put the mediaview.saveFile() method which refer to mediaView.ascx user control.
  • In this sample case, i am using the Typed dataset for binding into GridView which are when user pick the file which wanna upload then all of those URL image will be saved into the view state and then after that, when you want to save into your database or calling the CRUD , you need to move all from the viewstate into the dataset again ( you will find the complete sample MediaView.ascx in this code below )

      this is the listing complete code of MediaFileUpload.Aspx :

——————————————————————————————

      /*==================================================================================
 * Created By           : Doddy Ch Saputra, MCAD.NET
 * Created Date           : 03 May 2007
 * Last Modified By    : Doddy Ch Saputra
 * Last Modified date     : 03 May 2007
 * Architecture Template  : C# MyGeneration Doodads
 * Functionality          : Upload user control for Media
 * =================================================================================
 */
namespace ProcLearning.WebAdmin
{
 using System;
 using System.Data;
 using System.Drawing;
 using System.Web;
 using System.Web.UI.WebControls;
 using System.Web.UI.HtmlControls;
 using MyGeneration.dOOdads ;
 using System.Data.SqlClient;
 using System.Collections;
 using System.Collections.Specialized;
 using ProcLearning.FacadeLayer; 
 using ProcLearning.BindingLayer;
 using System.IO;

 /// <summary>
 ///  Summary description for MediaFileUpload.
 /// </summary>
 public class MediaFileUpload : ProcLearning.WebForm.FrontEnd.UserControl.UserControlBase
 {
  protected System.Web.UI.WebControls.Button RemvFile;
  string baseLocation=((string)System.Configuration.ConfigurationSettings.AppSettings.Get(“DataRequestRepository”));
  string webRepository=((string)System.Configuration.ConfigurationSettings.AppSettings.Get(“WebDataRequestRepository”));
  protected BunnyBear.msgBox Msgbox2;
  protected System.Web.UI.WebControls.Button Button2;
  protected System.Web.UI.WebControls.Label Label5;
  protected System.Web.UI.WebControls.Label Label6;
  protected ProcLearning.BindingLayer.Media media1;
  protected System.Web.UI.WebControls.TextBox txtMediaFileName;
  protected System.Web.UI.WebControls.TextBox txtDesc;
  protected System.Web.UI.HtmlControls.HtmlInputFile FindFile;
  protected System.Web.UI.WebControls.Button btnAdd;
  protected System.Web.UI.WebControls.Button btnSave;
  protected BunnyBear.msgBox MsgBox3;
  protected System.Web.UI.WebControls.Label Label1;
  protected System.Web.UI.WebControls.Label Label3;
  protected System.Web.UI.WebControls.DropDownList ddlType;
  protected System.Web.UI.WebControls.Label Label2;
  protected System.Web.UI.WebControls.Button AddFile;
  protected System.Web.UI.WebControls.Button btnSimpan;
  protected ProcLearning.WebAdmin.MediaView MediaView1;

  private void Page_Load(object sender, System.EventArgs e)
  {
  
  }
  public void Upload_ServerClick()
  {
   
   string status = “”;
   string fn =”";
   string URL=”";
   string ImageURL=”";
   int docID=0;
   DataRow dr;
   FileInfo fi;
   
   string idType=”";
   string TypeName=”";
   string URLName=”";
   

   fn = System.IO.Path.GetFileName(FindFile.PostedFile.FileName);
   string Ext = System.IO.Path.GetExtension(FindFile.PostedFile.FileName);

   string []Attribute=TypeFile(Ext).ToString().Split(‘|’);

   if (Ext.ToUpper() != “.DOC” && Ext.ToUpper() != “.WMV” && Ext.ToUpper() != “.MP3″ && Ext.ToUpper() != “.JPG” && Ext.ToUpper() != “.JPEG” && Ext.ToUpper() != “.PDF” && Ext.ToUpper() != “.VSD” && Ext.ToUpper() != “.XLS” && Ext.ToUpper() != “.PPT”)
   {
    this.MsgBox3.alert(“Please be advised that your file is in DOC,JPG,JPEG,XLS,PPT,VSD,PDF,WMV,MP3 format”);
   }
   else
   {
    idType=Attribute[0];
    TypeName=Attribute[1];
    URLName=Attribute[2];
   }
   if (this.txtMediaFileName.Text  == “”)
   {
               this.MsgBox3.alert(“Please be advised that your must fill the subject name of Media File “);
   }
   else
   if (this.txtDesc.Text == “”  )
   {
               this.MsgBox3.alert(“Please be advised that your must fill the description name of Media File “);
   }
   else
   if(FindFile.PostedFile.ContentLength>5000000)
   {
    this.MsgBox3.alert(“File Size should be smaller than 5 MB”);
   }
   else
   {
    try
    {
     FindFile.PostedFile.SaveAs(baseLocation + fn);

     // Bagian utk mengisi ke dataset sementara ——-is—————
       this.media1 = new Media();
       dr = this.media1.VW_Media.NewRow();
       dr["Media_Name"]= this.txtMediaFileName.ToString() ;
       dr["Type_Name"] = TypeName ;
       dr["Description"]=this.txtDesc.Text;
       dr["User_Name"]=base.CurrentUser.ToString();
       dr["Last_Updated"]= DateTime.Now;
       dr["URL"] = “/ProcLearning/DataRequestFileRepository/” + fn ;
       dr["Type_ID"] = idType;
       dr["Image_URL"] = URLName;
//       // ————————————————————–
     this.media1.VW_Media.Rows.Add(dr);
       
     status += fn + “<br>”;
     MediaView1.PrepareDocDS(this.txtMediaFileName.Text,TypeName,this.txtDesc.Text,base.CurrentUser.ToString(),”/ProcLearning/DataRequestFileRepository/” + fn,decimal.Parse(idType),URLName);

     this.txtMediaFileName.Text=”";
     this.txtDesc.Text=”";
                               
    }
    catch(Exception err)
    {
    }
   }
      
  }

  private string TypeFile(string Ekstension)
  {
            string Temp=”";          
           
    switch(Ekstension.ToUpper())
    {
     case “.DOC” :
      Temp = “2″ + “|” + “Word Document” + “|” + “/ProcLearning/WebFileRepository/Others/WORD.gif”;
      break;
     case “.WMV” :
      Temp = “3″ + “|” + “Video File” + “|” + “/ProcLearning/WebFileRepository/Others/Video.gif”;
      break;
     case “.MP3″ :
      Temp = “4″ + “|” + “Audio File” + “|” + “/ProcLearning/WebFileRepository/Others/WAV.gif”;
      break;
     case “.JPG” :
      Temp = “5″ + “|” + “Picture File” + “|” + “/ProcLearning/WebFileRepository/Others/Gambar.gif”;
      break;
     case “.JPEG” :
      Temp = “5″ + “|” + “Picture File” + “|” + “/ProcLearning/WebFileRepository/Others/Gambar.gif”;
      break;
     case “.PPT” :
      Temp = “6″ + “|” + “Presentation File” + “|” + “/ProcLearning/WebFileRepository/Others/Presentation.gif”;
      break;
     case “.XLS” :
      Temp = “7″ + “|” + “Spreadsheet File” + “|” + “/ProcLearning/WebFileRepository/Others/EXCEL.gif”;
      break;
     case “.VSD” :
      Temp = “8″ + “|” + “Visio File” + “|” + “/ProcLearning/WebFileRepository/Others/VISIO.gif”;
      break;
     case “.PDF” :
      Temp = “10″ + “|” + “Acrobat File” + “|” + “/ProcLearning/WebFileRepository/Others/PDF.gif”;
     break;
      
    }
    return Temp;
  }

  void getMediaType()
  {
   ProcLearning.Concrete.Master_Media_Type mediaType = new ProcLearning.Concrete.Master_Media_Type(); // Create Instance Object for Media Type

   mediaType.Where.Type_ID.Operator = WhereParameter.Operand.NotEqual;
   mediaType.Where.Type_ID.Value= 1;
                
   mediaType.Query.AddResultColumn(ProcLearning.Concrete.Master_Media_Type.ColumnNames.Type_ID);
   mediaType.Query.AddResultColumn(ProcLearning.Concrete.Master_Media_Type.ColumnNames.Type_Name );
   mediaType.Query.AddOrderBy(ProcLearning.Concrete.Master_Media_Type.ColumnNames.Type_Name ,WhereParameter.Dir.DESC );
     
   mediaType.Query.Load();

  }
  #region Web Form Designer generated code
  override protected void OnInit(EventArgs e)
  {
   //
   // CODEGEN: This call is required by the ASP.NET Web Form Designer.
   //
   InitializeComponent();
   base.OnInit(e);
  }
  
  /// <summary>
  ///  Required method for Designer support – do not modify
  ///  the contents of this method with the code editor.
  /// </summary>
  private void InitializeComponent()
  {
   this.media1 = new ProcLearning.BindingLayer.Media();
   ((System.ComponentModel.ISupportInitialize)(this.media1)).BeginInit();
   this.AddFile.Click += new System.EventHandler(this.AddFile_Click);
   this.btnSimpan.Click += new System.EventHandler(this.btnSimpan_Click);
   //
   // media1
   //
   this.media1.DataSetName = “Media”;
   this.media1.Locale = new System.Globalization.CultureInfo(“en-US”);
   this.Load += new System.EventHandler(this.Page_Load);
   ((System.ComponentModel.ISupportInitialize)(this.media1)).EndInit();

  }
  #endregion

  private void btnAdd_Click(object sender, System.EventArgs e)
  {
        
  }

  private void btnSave_Click(object sender, System.EventArgs e)
  {
   
  }

  private void btnSimpan_Click(object sender, System.EventArgs e)
  {
      MediaView1.Save();
  }

  private void AddFile_Click(object sender, System.EventArgs e)
  {
     Upload_ServerClick();

   if (Page.IsPostBack )
   {
    this.btnSimpan.Visible=true;
   }

  }

  
  
  
 }
}
——————————————————————————————

The code in MediaView.Ascx is :

/*==================================================================================
 * Created By           : Doddy Ch Saputra, MCAD.NET
 * Created Date           : 23 May 2007
 * Last Modified By    : Doddy Ch Saputra
 * Last Modified date     : 23 May 2007
 * Architecture Template  : C# MyGeneration Doodads
 * Functionality          : User Control for Media data uploading 
 * =================================================================================
 */
namespace ProcLearning.WebAdmin
{
 using System;
 using System.Data;
 using System.Drawing;
 using System.Web;
 using System.Web.UI.WebControls;
 using System.Web.UI.HtmlControls;
 using ProcLearning.BindingLayer;
 using ProcLearning.Configuration;

 /// <summary>
 ///  Summary description for MediaView.
 /// </summary>
 public class MediaView : ProcLearning.WebForm.FrontEnd.UserControl.UserControlBase
 {
  protected ProcLearning.BindingLayer.Media  Media1;
  protected System.Web.UI.WebControls.DataGrid dtgDoc;
  string webRepository=((string)System.Configuration.ConfigurationSettings.AppSettings.Get(“WebDataRequestRepository”));

  private void Page_Load(object sender, System.EventArgs e)
  {
   // Put user code to initialize the page here

   
  }
  public void DtgDocDataBind()
  {
   this.dtgDoc.DataBind();
  }
  
  public void Page_Change(object sender,  DataGridPageChangedEventArgs e)
  {
   int start = this.dtgDoc.CurrentPageIndex * this.dtgDoc.PageSize;
   this.dtgDoc .CurrentPageIndex= e.NewPageIndex;

   getMediaAllFiles();
  
  }
  protected void getMediaAllFiles()
  {
   ProcLearning.Concrete .VW_Media  media = new ProcLearning.Concrete.VW_Media (); // Create Instance Object for Media Type
   media.LoadAll();

   this.Media1 =this.DocDS;
   this.dtgDoc.DataBind();
  
  }

  public void PrepareDocDS(string MediaFileName,string TypeName,string Desc,string UserName,string URL,decimal TypeID,string ImageURL) // Updated By Doddy Chs 16 oktober 2006
  {
   this.Media1 =this.DocDS;
   DataRow dr = this.Media1.VW_Media.NewRow();
    dr["Media_Name"]= MediaFileName ;
    dr["Type_Name"] = TypeName ;
    dr["Description"]=Desc;
    dr["User_Name"]=UserName;
    dr["Last_Updated"]= DateTime.Now;
    dr["URL"] = URL ;
    dr["Type_ID"] = TypeID ;
    dr["Image_URL"] =ImageURL;
   // ————————————————————–
   this.Media1.VW_Media.Rows.Add(dr);
   this.DocDS=this.Media1;
   this.dtgDoc.DataBind();

   return;
  
  }
  
  public Media DocDS
  {
   get
   {
    Media ds=new Media();
    if(ViewState["MediaData"]!=null)
     ds=(Media)ViewState["MediaData"];
   
    return ds;
   }
   set
   {
    ViewState["MediaData"]=value;
    this.Media1 =value;
    this.dtgDoc.DataBind();

   }

  }

  public bool IsReadOnly
  {
   set
   {
    bool isVisible=true;
    if(value)isVisible=false;
    foreach (DataGridColumn col in this.dtgDoc.Columns)
    {
     if(col.HeaderText.Equals(“Delete”))
      col.Visible=isVisible;    

    }
   }
  }

  private void dtgDoc_DeleteCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
  {
   
   int i=0;
   int rowNum=0;
   this.Media1  =this.DocDS;

   foreach(DataRow dr in this.Media1.VW_Media.Rows )
   {
    if(!dr.RowState.Equals(DataRowState.Deleted))
    {
      rowNum=i;
    }
    i++;
   }

   DataRowCollection rc=this.Media1.VW_Media.Rows ;
   rc[rowNum].Delete();
   
   if((this.dtgDoc.Items.Count % this.dtgDoc.PageSize == 1) && (this.dtgDoc.CurrentPageIndex == this.dtgDoc.PageCount – 1) && (this.dtgDoc.CurrentPageIndex != 0))
   {
    this.dtgDoc.CurrentPageIndex = this.dtgDoc.CurrentPageIndex -1;
   }
   
 
   this.DocDS=this.Media1;
     
  }

  public void Save ()
  {
   decimal userID = decimal.Parse(Session["User_ID"].ToString());
           
   this.Media1  =this.DocDS;

   foreach(DataRow dr in this.Media1.VW_Media.Rows )
   {

    ProcLearning.Concrete.Portal_Media_Collection Trans = new ProcLearning.Concrete.Portal_Media_Collection();

    Trans.AddNew();
     Trans.Media_Name=dr["Media_Name"].ToString() ;
     Trans.Media_Type=decimal.Parse(dr["Type_ID"].ToString()) ;
     Trans.Description =dr["Description"].ToString();
     Trans.Updated_By = userID;
     Trans.Last_Updated = System.DateTime.Now ;
     Trans.Active=”Y”;
     Trans.URL = dr["URL"].ToString();
    Trans.Save();
    Response.Redirect(“/ProcLearning/WebForm/LessonModule/frmMultimediaLearning.aspx”,true);
   }
  }

  private void dtgDoc_ItemDataBound(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
  {
   Label lblDocID;
   string url=”";
   string docName=”";
   HyperLink hl=new HyperLink();
   if(e.Item.ItemType == ListItemType.Item || (e.Item.ItemType == ListItemType.AlternatingItem))
   {
    
    lblDocID = (Label) e.Item.FindControl(“lblDocID”);
    hl=(HyperLink)e.Item.Cells[2].Controls[0];
    docName=lblDocID.Text;
    url=this.webRepository+docName;
    hl.NavigateUrl =url;
   }
  }

  #region Web Form Designer generated code
  override protected void OnInit(EventArgs e)
  {
   //
   // CODEGEN: This call is required by the ASP.NET Web Form Designer.
   //
   InitializeComponent();
   base.OnInit(e);
  }
  
  /// <summary>
  ///  Required method for Designer support – do not modify
  ///  the contents of this method with the code editor.
  /// </summary>
  private void InitializeComponent()
  {
   this.Media1 = new ProcLearning.BindingLayer.Media();
   ((System.ComponentModel.ISupportInitialize)(this.Media1)).BeginInit();
   this.dtgDoc.DeleteCommand += new System.Web.UI.WebControls.DataGridCommandEventHandler(this.dtgDoc_DeleteCommand);
   //
   // Media1
   //
   this.Media1.DataSetName = “Media1″;
   this.Media1.Locale = new System.Globalization.CultureInfo(“en-US”);
   this.Load += new System.EventHandler(this.Page_Load);
   ((System.ComponentModel.ISupportInitialize)(this.Media1)).EndInit();

  }
  #endregion
 }
}


Entry Filed under: Development in C# 2.0, Dotnet Framework 2.0. .

Leave a Comment

Required

Required, hidden

Some HTML allowed:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <pre> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Trackback this post  |  Subscribe to the comments via RSS Feed


 

June 2007
M T W T F S S
    Jul »
 123
45678910
11121314151617
18192021222324
252627282930  

Categories

Recent Posts

Archives

Category Cloud

Design Pattern Code Development in C# 2.0 Development in C# 3.0 Dotnet Framework 2.0 Dotnet Framework 3.0 Own design custom Framework Pattern and Practise

Blog Stats

Top Posts

Blogroll

Recent Comments

Top Clicks

Feeds

Tags