分享

C# 实现多图片上传

 悟静 2014-04-28

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Text;
using System.IO;
using BusinessFacade.CustomerFacade;
using BusinessFacade.AmusementAndCateFacade;
using Common.CustomerCommon;
using System.Data.SqlClient ;
using Common.AmusementAndCateCommon;
namespace Web.AmusementAndCate.User
{
 /// <summary>
 /// MyAlbumUpLoad 的摘要说明。
 /// 创建人: 朱保健 创建日期:20071208
 /// </summary>
 public class MyAlbumUpLoad : PageBase
 {
  protected System.Web.UI.WebControls.DropDownList ddpAlbum;
  protected System.Web.UI.WebControls.Button Upload;
  protected System.Web.UI.WebControls.Button btnReturn;
  protected System.Web.UI.WebControls.Label strStatus;
  protected System.Web.UI.WebControls.Label lblphotoAlbumID;
  //  string photoAlbumID = string.Empty;
  //  string photoAlbumName = string.Empty;
  public string m_FileName = string.Empty;
  #region 初始化
  private void Page_Load(object sender, System.EventArgs e)
  {
   // 在此处放置用户代码以初始化页面
   //this.lblphotoAlbumID.Text = Request.QueryString["photoAlbumID"].ToString()!=string.Empty && Request.QueryString["photoAlbumID"].ToString()!= null?this.Check_Form(Request.QueryString["photoAlbumID"].ToString()):string.Empty;
  // MyTitle.Text = "<h3>多个图片同时上传</h3>";
   Upload.Text = "开始上传";
   if(!IsPostBack)
   {
    if(this.UserCode>0)
    {
     DropDownListBind();
    }
    else
    {
     GetUserCode(this.UserCode,"AmusementAndCate","Login/login.aspx");
    }

   }
  }

  #region 绑定DropDownList
  private void DropDownListBind()
  {
   int count = new PerAlbumFacade().GetAlbumCountByPerID(this.UserCode);
   if(count==0)
   {
    ddpAlbum.Items.Add(new ListItem("我的相册","100001"));
   }
   else
   {
    SqlDataReader myReader  = new PerAlbumFacade().GetShowPhotoAlbumInfoByPerID(this.UserCode.ToString());
    while(myReader.Read() )
    {
     ddpAlbum.Items.Add(new ListItem(myReader["PhotoAlbumName"].ToString(),myReader["PhotoAlbumID"].ToString()));
    }
   }
  }
  #endregion
  #endregion

  #region Web 窗体设计器生成的代码
  override protected void OnInit(EventArgs e)
  {
   //
   // CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。
   //
   InitializeComponent();
   base.OnInit(e);
  }
  
  /// <summary>
  /// 设计器支持所需的方法 - 不要使用代码编辑器修改
  /// 此方法的内容。
  /// </summary>
  private void InitializeComponent()
  {   
   this.Upload.Click += new System.EventHandler(this.Upload_Click);
   this.btnReturn.Click += new System.EventHandler(this.btnReturn_Click);
   this.Load += new System.EventHandler(this.Page_Load);

  }
  #endregion

  #region 将图片插入到数据库中
  private void InsertIntoTab(int id,string UpLoadImagesSaveUrl,DateTime CurTime,int tempWidth,int tempHeight,string photoAlbumID)
  {
   PerAlbumData peralbum = new PerAlbumData();
   DataTable table = peralbum.Tables[PerAlbumData.PERALBUM_TAB];
   DataRow row = table.NewRow();
   row[PerAlbumData.PERID_FIELD] = id;
   row[PerAlbumData.PHOTONAME_FIELD] = this.ddpAlbum.SelectedItem.Text.Trim();
   row[PerAlbumData.PHOTOURL_FIELD] = UpLoadImagesSaveUrl+"/"+m_FileName;
   row[PerAlbumData.INTRODUCE_FIELD] = "";
   row[PerAlbumData.TYPE_FIELD] = 0;
   row[PerAlbumData.UPLOADDATE_FIELD] = CurTime;
   row[PerAlbumData.STATUS_FIELD] = 1;
   row[PerAlbumData.ISOPEN_FIELD] = 1;
   row[PerAlbumData.PWIDTH_FIELD] = tempWidth;
   row[PerAlbumData.PHEIGHT_FIELD] = tempHeight;
   row[PerAlbumData.PHOTOALBUMID_FIELD] = photoAlbumID;
   table.Rows.Add( row );
   bool result = (new PerAlbumFacade()).InsertPerPhotoFacade(peralbum);//(new FellowRegisterFacade()).InsertFellowRegister(fellowregisterData);
  }
  #endregion

  private void MultiFileUpload()
  {
   string mPath = string.Empty;//服务器上传路径
   string mFileName = string.Empty;
   int tempWidth = 0; 
   int tempHeight = 0; 
   //定义上载文件的列表
   HttpFileCollection fileList = HttpContext.Current.Request.Files;
   //存放上载文件的操作消息
   StringBuilder uploadMessage = new StringBuilder("当前上传的文件分别是:<hr color=red>");
   int fileIndex = 0;
   
   try
   {
    ///上载文件列表中的每一个文件
    string photoAlbumID = ddpAlbum.SelectedValue.ToString();
    string ImagesSaveUrl = "../uploadImg/"+this.UserCode.ToString()+"/";
    string UpLoadImagesSaveUrl = ImagesSaveUrl;

    for(fileIndex = 0; fileIndex < fileList.Count; fileIndex++)
    {
     ///获取当前上载的文件
     HttpPostedFile postedFile = fileList[fileIndex];
     String fileName = string.Empty;
     String fileExtension = string.Empty;
     DateTime CurTime = DateTime.Now;
     //获取上载文件的文件名称
     fileName = Path.GetFileName(postedFile.FileName);
     m_FileName = fileName;
     //获取上载文件的扩展名称
     fileExtension = Path.GetExtension(fileName);
     if(fileName != null)
     {
      if (fileList[fileIndex].FileName.Length > 0)
      {
       if (postedFile.ContentLength / 512 > 512)//单个图片不能大于512k
       {
        uploadMessage.Append(Path.GetFileName(postedFile.FileName) + "---不能大于1024k<br>");
        break;
       }
      }
      //上载图片
      if(fileExtension != ".jpg" && fileExtension != ".gif" && fileExtension != ".swf")
      {
       uploadMessage.Append(Path.GetFileName(postedFile.FileName) + "---图片格式不对,只能是jpg或gif或swf<br>");
       break;
      }
      System.Drawing.Image image = System.Drawing.Image.FromStream( postedFile.InputStream );
      //获取上传的图片宽和高
      tempWidth = Convert.ToInt32( image.Width ); 
      tempHeight = Convert.ToInt32( image.Height ); 
      if(tempWidth >100)
      {
       strStatus.Text = "图片的宽度不能大于100像素";
       Response.Redirect("MyAlbumUpLoad.aspx");
      }
      if(tempHeight>120)
      {
       strStatus.Text = "图片的高度不能大于120像素";
       Response.Redirect("MyAlbumUpLoad.aspx");
      }
     }
     uploadMessage.Append("上传的文件类型:" + postedFile.ContentType.ToString() + "<br>");
     uploadMessage.Append("客户端文件地址:" + postedFile.FileName + "<br>");
     uploadMessage.Append("上传文件的文件名:" + fileName + "<br>");
     uploadMessage.Append("上传文件的扩展名:" + fileExtension + "<br><hr>");

     //上载文件  
     bool isValid=false;  
     mPath= Server.MapPath(UpLoadImagesSaveUrl);   //服务器上传路径
     mFileName= mPath+fileName;
     FileInfo TheFile = new FileInfo(mFileName);
     //文件不存在,判断目录是否存在
     DirectoryInfo TheFolder = new DirectoryInfo(mPath+"//");//目录是否存在

     if(TheFile.Exists)
     {
      //文件存在
      //更换文件名称
      mFileName = Path.GetDirectoryName( mPath ) +"/"+DateTime.Now.ToShortDateString()+fileExtension;
     }
     else
     {
      
      if (TheFolder.Exists)
      {
       //目录存在不需要新建文件夹
      }
      else
      {
       //创建文件夹
       DirectoryInfo d=Directory.CreateDirectory(mPath+"//");
      }
     }
     postedFile.SaveAs(mFileName);
     if(mFileName.Length>0)  //如果有上传文件
     {
      isValid=true;
     }
     #region 将图片插入到数据库中
     if(isValid)
     {
      InsertIntoTab(this.UserCode,UpLoadImagesSaveUrl,CurTime,tempWidth,tempHeight,photoAlbumID);
     }
     #endregion
    }

    //显示上载文件的操作成功消息
    strStatus.Text = uploadMessage.ToString();
   }
   catch(Exception ex)
   {
    ///显示上载文件的操作失败消息
    strStatus.Text = ex.Message;
   }
  }

  private void Upload_Click(object sender, System.EventArgs e)
  {
   //上载图片
   MultiFileUpload();
   Response.Redirect("MyAblumShow.aspx?photoAlbumID="+this.ddpAlbum.SelectedValue.ToString());
  }

  private void btnReturn_Click(object sender, System.EventArgs e)
  {
   Response.Redirect("MyAlbumUpLoad.aspx");
  }

 }
}

 <LINK href="../css/style.css" type="text/css" rel="stylesheet">
  <LINK href="../css/cate.css" type="text/css" rel="stylesheet">
  <script type="text/javascript">
   var i=1
   function addFile()
   {
   if (i<6)
     {var str = '<BR> <input type="file" name="File"

runat="server" style="width: 300px"/>'
    document.getElementById

('MyFile').insertAdjacentHTML("beforeEnd",str)
   }
   else
   {
    alert("您一次最多只能上传6张图片!")
   }
   i++
   }
  </script>

<form id="form1" method="post" runat="server">
  <div style="width:700">
   <TABLE id="Table1" height="380" cellSpacing="0"

cellPadding="0" width="700" border="0">
    <TR>
     <TD class="font" style="PADDING-TOP: 3px"

noWrap height="10" vAlign=top>相册:</TD>
     <TD class="font" noWrap height="10"

vAlign=top><asp:dropdownlist id="ddpAlbum" runat="server"

Width="150px"></asp:dropdownlist>  <br>
      <A href="MyNewAlbum.aspx"

target="_self">我要新建相册</A></TD>
    </TR>
    <TR>
     <TD style="WIDTH: 44px"></TD>
     <TD vAlign="top"><font

color="#ff0000">*</font>图片的宽度不能大于100像素,高度不能大于120像素,多个图片可以

同时上传<br>
      <P id="MyFile"><INPUT

style="WIDTH: 300px" type="file" name="File"></P>
      <P><input onclick="addFile()"

type="button" value="增加(Add)">
       <asp:button id="Upload"

Width="60px" Runat="server" Text="上  传"></asp:button><asp:button id="btnReturn"

Width="60px" Runat="server" Text="重 置"></asp:button></P>
      <P><asp:label id="strStatus"

style="FONT-WEIGHT: 600; FONT-SIZE: 12px; BORDER-LEFT-COLOR: #ffffff; BORDER-

BOTTOM-COLOR: #ffffff; BORDER-TOP-STYLE: none; BORDER-TOP-COLOR: #ffffff; PADDING

-TOP: 250px; BORDER-RIGHT-STYLE: none; BORDER-LEFT-STYLE: none; BORDER-RIGHT-

COLOR: #ffffff; BORDER-BOTTOM-STYLE: none"
        

runat="server"></asp:label></P>
     </TD>
    </TR>
   </TABLE>
   </div>
   <asp:Label id="lblphotoAlbumID" runat="server"

Visible="False"></asp:Label>
  </form>

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多