我的页面是这样子的:一个FileUpload控件,一个上传的按钮,一个确定的按钮
选择所需的图片,点击上传,就可以在页面预览图片,不过是用的js实现的,可以同时显示多张图片,
点击确定,就可能将显示的所有图片上传到服务器,我只有一个FileUpload控件,不会动态生成FileUpload控件,
后台代码该如何实现?

解决方案 »

  1.   

    我刚刚做了一个图片管理的呵呵,就是动态生成的FileUpload,跟你说的一样。。把你JS写的代码也发我看下吧,我JS蛮差的呵呵。using System;
    using System.Collections;
    using System.Configuration;
    using System.Data;
    using System.Linq;
    using System.Web;
    using System.Web.Security;
    using System.Web.UI;
    using System.Web.UI.HtmlControls;
    using System.Web.UI.WebControls;
    using System.Web.UI.WebControls.WebParts;
    using System.Xml.Linq;
    using System.Data.OleDb;
    using System.IO;public partial class Default2 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)//首次执行页面
            {
                SFUPC();//页面执行一次将上传文件控件集到缓存中
            }
        }    protected void Btn_onLoad_Click(object sender, EventArgs e)
        {
            UpFile();//执行上传文件
        }
        protected void Btn_Add_Click(object sender, EventArgs e)
        {
            InsertC();//执行添加控件方法
        }    protected void Btn_Seeinfo_Click(object sender, EventArgs e)
        {
            Response.Redirect("Default.aspx");
        }    private void SFUPC()//该方法用于保存当前页面上传文件控件集到缓存中
        {
            ArrayList AL = new ArrayList();//创建动态增加数组
            foreach (Control C in F.Controls)
            {
                if (C.GetType().ToString() == "System.Web.UI.HtmlControls.HtmlTableRow")
                {
                    HtmlTableCell HTC = (HtmlTableCell)C.Controls[0];
                    foreach (Control FUC in HTC.Controls)
                    {
                        if (FUC.GetType().ToString() == "System.Web.UI.WebControls.FileUpload")
                        {
                            FileUpload FU = (FileUpload)FUC;
                            AL.Add(FU);
                        }
                    }
                }
            }
            Session.Add("FilesControls", AL);
        }
        private void InsertC()//该方法用于添加一个上传文件的控件
        {
            ArrayList AL = new ArrayList();
            this.F.Rows.Clear();
            GetInfo();
            HtmlTableRow HTR = new HtmlTableRow();
            HtmlTableCell HTC = new HtmlTableCell();
            HTC.Controls.Add(new FileUpload());
            HTR.Controls.Add(HTC);
            F.Rows.Add(HTR);
            SFUPC();
        }
        private void GetInfo()//该方法用于读取缓存中存储的上传文件控件集
        {
            ArrayList AL = new ArrayList();
            if (Session["FilesControls"] != null)
            {
                AL = (System.Collections.ArrayList)Session["FilesControls"];
                for (int i = 0; i < AL.Count; i++)
                {
                    HtmlTableRow HTR = new HtmlTableRow();
                    HtmlTableCell HTC = new HtmlTableCell();
                    HTC.Controls.Add((System.Web.UI.WebControls.FileUpload)AL[i]);
                    HTR.Controls.Add(HTC);
                    F.Rows.Add(HTR);
                }
            }
        }
        private void UpFile()//该方法用于执行文件上传操作
        {
            string FilePath = Server.MapPath("./") + "Images";        HttpFileCollection HFC = Request.Files;
            for (int i = 0; i < HFC.Count; i++)
            {
                HttpPostedFile UserHPF = HFC[i];
                string FileExtend = UserHPF.FileName.Substring(UserHPF.FileName.LastIndexOf(".") + 1);
                string Filename = UserHPF.FileName.Substring(UserHPF.FileName.LastIndexOf("\\") + 1);
                try
                {
                    if (UserHPF.ContentLength > 0)
                    {                    if (FileExtend == "jpg" || FileExtend == "bmp" || FileExtend == "gif" || FileExtend=="png")
                        {
                            if (UserHPF.ContentLength > (800* 600))
                            {
                                Response.Write("<script language=javascript>alert('你选择的图片太大!');location='Default2.aspx'</script>");
                            }
                            UserHPF.SaveAs(FilePath + "\\" + System.IO.Path.GetFileName(UserHPF.FileName));
                            OleDbConnection myCon = DB.Creatconnection();
                            myCon.Open();
                            string comStr = "insert into Imageinfo(ImageFileName,ImageFilePath,ImageDatetime) values('" + Filename + "','"
                                + FilePath + "','" + DateTime.Now.ToShortDateString()+ "')";                      
                            OleDbCommand myCom = new OleDbCommand(comStr, myCon);
                            myCom.ExecuteNonQuery();
                            myCon.Close();
                            Response.Write("<script language=javascript>alert('上传成功!');location='Default.aspx'</script>");
                        }
                        else
                        {
                            Response.Write("<script language=javascript>alert('你选择的图片格式不正确!');location='Default2.aspx'</script>");
                        }
                    }
                }
                catch (Exception ex)
                {
                    Response.Write("<script language=javascript>alert('+" + ex.Message + "');location='Default.aspx'</script>");
                }
            }
            if (Session["FilesControls"] != null)
            {
                Session.Remove("FilesControls");
            }
        }
    }
    应该对你有用。自己慢慢看吧
      

  2.   

    主要就是这个 
                   private void InsertC()//该方法用于添加一个上传文件的控件
      

  3.   

    <%@ Page Language="C#" AutoEventWireup="true" CodeFile="UploadPicture.aspx.cs" Inherits="supply_UploadPicture" %><%@ Register Assembly="System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
        Namespace="System.Web.UI" TagPrefix="asp" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml" >
    <head id="Head1" runat="server">
        <title>无标题页</title>
         
        <style type="text/css">
        .TableData   { BACKGROUND: #FFFFFF;COLOR:#000000;}
        .TableHeader { BACKGROUND: #D3E5FA; COLOR:#3F3F7E; FONT-WEIGHT: bold; FONT-SIZE: 11pt; background-image: url("/theme/1/headerbg.gif") }
        </style>
        
        <script type="text/javascript">
            function GetImage()
            {          
                var file=document.getElementById("fileUpload").value;
               // alert(file);
                
                document.getElementById("images").innerHTML=document.getElementById("images").innerHTML+"<div><img src='"+file+"' width='100' height='100'/><br/>删除</div>";
                
                document.getElementById("txtImage").value=document.getElementById("txtImage").value+";"+file;            
            }
        
        </script>
    </head>
    <body style="font-size: 11pt;">
        <form id="form1" runat="server">
        <b>发布供求信息>>图片管理</b> <div>
            &nbsp;</div>
        <hr style="border-right: #3366ff thick groove; border-top: #3366ff thick groove;
                    border-left: #3366ff thick groove; border-bottom: #3366ff thick groove" />
                       <div class="mframe" >
                           &nbsp;</div>
                           <div>
            <table align="center" bgcolor="#000000" border="0" cellpadding="3" cellspacing="1"
                  style="font-size:9pt; border:4px solid #3366FF;"
                width="80%">
                <tr class="TableHeader">
                    <td class="tm" style="width: 776px; height: 24px;">
                        <span class="tt">*您的供求信息已保存,请继续添加图片</span></td>               
                </tr>
                <tr class="TableData">
                   
                    <td align="center">
                    
                    <div style="margin-top:20px; margin-bottom:20px; border:1px solid; width:90%;" >
                                  <p style=" margin-top:20px;"> 图片管理(上传图片): &nbsp; &nbsp; &nbsp;&nbsp; &nbsp;&nbsp;&nbsp;<asp:FileUpload ID="fileUpload"
                                          runat="server" Height="23px" Width="277px" />&nbsp;<input id="btnUpload"
                                          type="button" value="上传" onclick="GetImage()"/></p>
                                        
                                        
                                     <hr style="width:95%; border:1px solid #cccccc;"/>
                                        <div  style="width:100%; height:120px;" id="images">
                                            <input id="txtImage" runat="server" style="z-index: 100; left: 258px; position: absolute;
                                                top: 14px" type="hidden" />
                                            &nbsp;</div>
                                        <hr style="width:95%; border:1px solid #cccccc;" />
                                        <p>
                                            <asp:Button ID="btnOK" runat="server" Text="确定" Width="55px" />&nbsp;&nbsp; &nbsp;
                                            &nbsp;
                                            <asp:Button ID="btnBack" runat="server" Text="返回" Width="55px" /></p>
                        <p>
                            &nbsp;</p>
                                 </div>
                       </td>                   
                </tr>
            </table>
            </div>      
     
        </form>
    </body>
    </html>这是我的aspx页面的源码,后台还没有写代码
      

  4.   

    我也需要一个批量上传图片的源码。
       保存二进制流文件到数据库对应Image类型,不是保存相对路径的。
    有的话麻烦请发给我,给100分作为奖励。
      

  5.   

    用我的,多文件上传JS生成上传C# 版本UpLoad.aspx<%@ Page language="c#" Codebehind="UpLoad.aspx.cs" AutoEventWireup="false" Inherits="WebPortal.Upload" %>
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
    <HTML>
      <HEAD>
        <title>多文件上传</title>
        <script language="JavaScript">
        function addFile()
        {
         var str = '<INPUT type="file" size="50" NAME="File">'
         document.getElementById('MyFile').insertAdjacentHTML("beforeEnd",str)
        }
        </script>
      </HEAD>
      <body>
        <form id="form1" method="post" runat="server" enctype="multipart/form-data">
          <div align="center">
            <h3>多文件上传</h3>
            <P id="MyFile"><INPUT type="file" size="50" NAME="File"></P>
            <P>
              <input type="button" value="增加(Add)" onclick="addFile()">
              <input onclick="this.form.reset()" type="button" value="重置(ReSet)">
              <asp:Button Runat="server" Text="开始上传" ID="UploadButton"></asp:Button>
            </P>
            <P>
            <asp:Label id="strStatus" runat="server" Font-Names="宋体" Font-Bold="True" Font-Size="9pt" 
              Width="500px" BorderStyle="None" BorderColor="White"></asp:Label>
            </P> 
          </div>
        </form>
      </body>
    </HTML>
    UpLoad.aspx.csusing 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;namespace WebPortal
    {
      /// <summary>
      /// UpLoad 的摘要说明。
      /// 实现多文件上传
      /// </summary>
      public class Upload : System.Web.UI.Page
      {
        protected System.Web.UI.WebControls.Button UploadButton;
        protected System.Web.UI.WebControls.Label strStatus;    private void Page_Load(object sender, System.EventArgs e)
        {
          /// 在此处放置用户代码以初始化页面
          if (this.IsPostBack) this.SaveImages();
        }    private Boolean SaveImages()
        {
          ///'遍历File表单元素
          HttpFileCollection files  = HttpContext.Current.Request.Files;      /// '状态信息
          System.Text.StringBuilder strMsg = new System.Text.StringBuilder();
          strMsg.Append("上传的文件分别是:<hr color=red>");
          try
          {
            for(int iFile = 0; iFile < files.Count; iFile++)
            {
              ///'检查文件扩展名字
              HttpPostedFile postedFile = files[iFile];
              string fileName, fileExtension;
              fileName = System.IO.Path.GetFileName(postedFile.FileName);
              if (fileName != "")
              {
                fileExtension = System.IO.Path.GetExtension(fileName);
                strMsg.Append("上传的文件类型:" + postedFile.ContentType.ToString() + "<br>");
                strMsg.Append("客户端文件地址:" + postedFile.FileName + "<br>");
                strMsg.Append("上传文件的文件名:" + fileName + "<br>");
                strMsg.Append("上传文件的扩展名:" + fileExtension + "<br><hr>");
                ///'可根据扩展名字的不同保存到不同的文件夹
                ///注意:可能要修改你的文件夹的匿名写入权限。
                postedFile.SaveAs(System.Web.HttpContext.Current.Request.MapPath("images/") + fileName);
              }
            }
            strStatus.Text = strMsg.ToString();
            return true;
          }
          catch(System.Exception Ex)
          {
            strStatus.Text = Ex.Message;
            return false;
          }
        }
      #region Web 窗体设计器生成的代码
      override protected void OnInit(EventArgs e)
      {
      //
      // CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。
      //
      InitializeComponent();
      base.OnInit(e);
      }  /// <summary>
      /// 设计器支持所需的方法 - 不要使用代码编辑器修改
      /// 此方法的内容。
      /// </summary>
      private void InitializeComponent()
      {    
        this.ID = "Upload";
        this.Load += new System.EventHandler(this.Page_Load);  }
      #endregion
      }
    }
      

  6.   

    建议你用“swfupload" 很简单,也很方便,一次可以选多个文件,自带进度条,美观。