ASP.NET(C#)实现一次性上传多张图片(多个文件)

在做asp.net的Web开发的时候,我们经常会遇到一次性上传多个文件的需求。通常我们的解决方法是固定放多个上传文件框,这样的解决办法显然是不合理的,因为一次上传多个,就意味着数量不确定。因此我们就要让这些文件上传框动态添加,下面我以我做的一个图库管理中的上传图片的功能为例

先看效果:
打开的初始界面:


默认是上传一个图片,但当我们点“增加图片”按钮时可以实现选择多个图片及其描述同时上传,本功能限制一次最多只能上传8张,且每张图片大小不超过1M,这个大家可根据实际情况更改!
如图:


下面来看实现过程:

第一步,使用javascript代码实现动态添加文件上传框和描述文本框,关键代码如下:


<script type="text/javascript">
        var i=1
        function addFile()
        ...{
    
         if (i<8)
            ...{var str = '<BR> <input type="file" name="File" runat="server" style="width: 300px"/>描述:<input name="text" type="text" style="width: 150px" maxlength="20" />'
            document.getElementById('MyFile').insertAdjacentHTML("beforeEnd",str)
       
            }
        else
            ...{
                alert("您一次最多只能上传8张图片!")
            }
            i++
        }
        </script>HTML调用代码为:
<P id="MyFile"><INPUT οnclick="addFile()" type="button" value="增加图片(Add)"><br />
                                    <input type="file" name="File" runat="server" style="width: 300px"/>
                                    描述:<input name="text" type="text" style="width: 150px" maxlength="20" />

第二步:服务器端代码实现
就上传单个文件或图片来说,使最普通不 过的了,但是对于这样的一次性上传多个文件以及它们相应的描述的问题,就要费点周折

    首先,通过System.Web.HttpContext.Current.Request.Files方法获取客户端的文件集合,然后通过Request.Form方法获得描述文本框集合,最后利用一个循环将文件上传,并将相应的信息保存到数据库
关键代码如下:


System.Web.HttpFileCollection files = System.Web.HttpContext.Current.Request.Files;
        string[] rd = Request.Form[1].Split(',');//获得图片描述的文本框字符串数组,为对应的图片的描述
        string albumid=ddlAlbum.SelectedValue.Trim();
        int ifile;
        for (ifile = 0; ifile < files.Count; ifile++)
        ...{
            if (files[ifile].FileName.Length > 0)
            ...{
                      ..........................  //上传单个文件并保存相关信息
             }
         }
最后给出上述功能的全部代码:

HTML代码:


<%...@ Page Language="C#" AutoEventWireup="true" CodeFile="UploadImg.aspx.cs" Inherits="NetAdmin_APicture_UploadImg" %>

<!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 runat="server">
    <title>无标题页</title>
        <script type="text/javascript">...
        var i=1
        function addFile()
        ...{
    
         if (i<8)
            ...{var str = '<BR> <input type="file" name="File" runat="server" style="width: 300px"/>描述:<input name="text" type="text" style="width: 150px" maxlength="20" />'
            document.getElementById('MyFile').insertAdjacentHTML("beforeEnd",str)
       
            }
        else
            ...{
                alert("您一次最多只能上传8张图片!")
            }
            i++
        }
        </script>
    <link href="../../NetAdmin/Site.Css" rel="stylesheet" type="text/css" />
</head>
<body style="background-image: url(../images/bg.jpg); text-align: center">
    <form id="form1" runat="server">
    <div>
        <table id="Table1" align="center" border="0" cellpadding="1" cellspacing="1" class="table"
            style="height: 58px" width="620">
            <tr>
                <td align="center" background="../images/topbg1.jpg">
                    <font color="#0000ff" face="宋体" size="3"><strong>上传图片</strong></font></td>
            </tr>
            <tr>
                <td align="center">
                    &nbsp;</td>
            </tr>
            <tr>
                <td align="center">
                    <asp:Panel ID="Panel5" runat="server" Width="608px">
                        &nbsp; &nbsp;<table width="100%">
                            <tr>
                                <td align="right" style="width: 100px">
                                </td>
                                <td align="left">
                                    说明:点增加图片按钮可一次上传多张图片,可为每张图片写上一句不超过20个字的描述。单张图片大小不大于1024k</td>
                            </tr>
                            <tr>
                                <td align="right" style="width: 100px">
                                    请选择图片:<br />
                                </td>
                                <td align="left"><P id="MyFile"><INPUT οnclick="addFile()" type="button" value="增加图片(Add)"><br />
                                    <input type="file" name="File" runat="server" style="width: 300px"/>
                                    描述:<input name="text" type="text" style="width: 150px" maxlength="20" />
                                </td>
                            </tr>
                            <tr>
                                <td align="right" style="width: 100px">
                                    上传到的图库:</td>
                                <td align="left">
                                    <asp:DropDownList ID="ddlAlbum" runat="server" DataSourceID="SqlDataSource1"
                                        DataTextField="AlbumName" DataValueField="AlbumID">
                                    </asp:DropDownList><asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:WebJakeCS %>"
                                        SelectCommand="SELECT [AlbumID], [AlbumName] FROM [WB_Album] ORDER BY [AlbumID] DESC">
                                    </asp:SqlDataSource>
                                </td>
                            </tr>
                            <tr>
                                <td align="right" style="width: 100px">
                                </td>
                                <td align="left">
                                    <asp:Button ID="btnUpload" runat="server" Text="开始上传" OnClick="btnUpload_Click" />
                                    </td>
                            </tr>
                            <tr>
                                <td align="right" style="width: 100px">
                                </td>
                                <td align="left">
                                    <asp:Label ID="lblMessage" runat="server" Font-Bold="True" ForeColor="Red"></asp:Label></td>
                            </tr>
                        </table>
                    </asp:Panel>
                    &nbsp;
                </td>
            </tr>
            <tr>
                <td align="center">
                    <font face="宋体"></font><font face="宋体">&nbsp;</font>
                </td>
            </tr>
            <tr>
                <td align="center">
                    <font face="宋体"></font>
                </td>
            </tr>
        </table>
   
    </div>
    </form>
</body>
</html>
后台代码:
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
public partial class NetAdmin_APicture_UploadImg : System.Web.UI.Page
...{
    protected void Page_Load(object sender, EventArgs e)
    ...{

    }
  
    protected void btnUpload_Click(object sender, EventArgs e)
    ...{
        lblMessage.Text = "";
        lblMessage.Visible = false;
        System.Web.HttpFileCollection files = System.Web.HttpContext.Current.Request.Files;
        System.Text.StringBuilder strmsg = new System.Text.StringBuilder("");
        string[] rd = Request.Form[1].Split(',');//获得图片描述的文本框字符串数组,为对应的图片的描述
        string albumid=ddlAlbum.SelectedValue.Trim();
        int ifile;
        for (ifile = 0; ifile < files.Count; ifile++)
        ...{
            if (files[ifile].FileName.Length > 0)
            ...{
                System.Web.HttpPostedFile postedfile = files[ifile];
                if (postedfile.ContentLength / 1024 > 1024)//单个文件不能大于1024k
                ...{
                    strmsg.Append(Path.GetFileName(postedfile.FileName) + "---不能大于1024k<br>");
                    break;
                }
                string fex = Path.GetExtension(postedfile.FileName);
                if (fex != ".jpg" && fex != ".JPG" && fex != ".gif" && fex != ".GIF")
                ...{
                    strmsg.Append(Path.GetFileName(postedfile.FileName) + "---图片格式不对,只能是jpg或gif<br>");
                    break;
                }
            }
        }
        if (strmsg.Length <= 0)//说明图片大小和格式都没问题
        ...{
            //以下为创建图库目录
            string dirname = "pic00" + ddlAlbum.SelectedValue.Trim();
            string dirpath = Server.MapPath("../../PicBase");
            dirpath = dirpath + "/" + dirname;
            if (Directory.Exists(dirpath) == false)
            ...{
                Directory.CreateDirectory(dirpath);
            }
            Random ro = new Random();
            int name = 1;
            for (int i = 0; i < files.Count; i++)
            ...{
                System.Web.HttpPostedFile myFile = files[i];
                string FileName = "";
                string FileExtention = "";
                string PicPath = "";
                FileName = System.IO.Path.GetFileName(myFile.FileName); 
                string stro=ro.Next(100,100000000).ToString()+name.ToString();//产生一个随机数用于新命名的图片
                string NewName =DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString()+DateTime.Now.Millisecond.ToString()+stro;
                if (FileName.Length > 0)//有文件才执行上传操作再保存到数据库
                ...{
                    FileExtention = System.IO.Path.GetExtension(myFile.FileName);

                    string ppath = dirpath + "/" + NewName + FileExtention;
                    myFile.SaveAs(ppath);
                    string FJname = FileName;
                    PicPath = "PicBase" + "/" + dirname + "/" + NewName + FileExtention;
                  
                }
                AddPicture(PicPath, rd[i], albumid);//将图片信息保存到数据库
                if (name == 1)//如果为每次更新的第一张图片,则将它更新为象册的封面
                ...{
                    upFirstimg(albumid, PicPath);
                }
                name = name + 1;//用来重命名规则的变量
               
            }
        }
        else
        ...{
            lblMessage.Text = strmsg.ToString();
            lblMessage.Visible = true;
        }
    }
    private void AddPicture(string imgpath,string imgnote,string albumid)
    ...{
        string sql = "insert WB_AlbumImges(ImgPath,ImgNote,AlbumID) values('"+imgpath+"','"+imgnote+"','"+albumid+"')";
        DB mydb = new DB();
        mydb.RunProc(sql);
    }
    private void upFirstimg(string albumid,string firstimg)
    ...{
        string sql = "update WB_Album set FirstImg='"+firstimg+"' where AlbumID="+albumid;
        DB mydb = new DB();
        mydb.RunProc(sql);
    }
}


本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/j_jake/archive/2007/09/06/1774544.aspx

 

 

 

 

 

 

 

 

JavaScript动态添加和删除控件

 

 

< input type = " button "  onClick = " add(); "  value = " 添加控件 " >
 < div id = " a " >
 
 </ div >
 < script >
 var  num = 0 ;
  function  add() ... {
 alert(window.document.getElementById( " a " ).innerHTML);
 window.document.getElementById( " a " ).innerHTML = window.document.getElementById( " a " ).innerHTML  +   " <br/><input type='text' id='up " + num + " '><a href='#' onClick='javascript:del( " + num + " );'>删除此控件 " + num + " </a> " ; 
 num = num + 1 ;
 }
  function  del(n) ... {
 var  str = window.document.getElementById( " a " ).innerHTML;
 var  regEx = new  RegExp( " <BR><[^<>]*(up " + n + " ){1}[^<>]*><[^<>]*>[^<>]*</A> " );
 str = str.replace(regEx, "" );
 alert(str);
 window.document.getElementById( " a " ).innerHTML = str;
 }
 </ script >
方法二
//动态添加或删除新的文本框
var num=0;
function add(){
    var html="<input type='text' value='' name='poll[]' id='up"+num+"'><a href='#' onClick='javascript:del("+num+");' id='delBtn_"+num+"'>删除此项</a><br/>";
    new Insertion.Top('addInput',html);
    num=num+1;
}
function del(n){
    var node=document.getElementById("up"+n);
    var delButton=document.getElementById("delBtn_"+n);
    if(node){
        node.parentNode.removeChild(node);
        delButton.parentNode.removeChild(delButton);
    }
}

 

本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/saiusky/archive/2009/07/03/4319789.aspx

 

 

 

详细代码

 

     <script type="text/javascript">
    var num=1;
    function addFile()
    {
    if(num<8)
    {
        var html="<br id='br"+num+"' /><input type='file' style='width: 300px;height:24px;' id='up"+num+"'><input onClick='javascript:del("+num+");' id='delBtn_"+num+"' type='button' value='删除' />";
        document.getElementById('MyFile').insertAdjacentHTML("beforeEnd",html);          
        num=num+1;  
        }
        else
        {
         alert("您一次最多只能上传8张图片!");
        }

    }
    function del(n)
    {
     var brnode=document.getElementById("br"+n);
     var node=document.getElementById("up"+n);
     var delButton=document.getElementById("delBtn_"+n);
        if(node)
        {
        node.parentNode.removeChild(node);
        delButton.parentNode.removeChild(delButton);
        brnode.parentNode.removeChild(brnode);
      
        }
        num=num-1;
    }    
    </script>

 

 

  <P id="MyFile">
                                    <input id="File1" type="file" name="File" runat="server" style="width: 300px;height:24px;"/><input οnclick="addFile()" type="button" value="增加图片" /></P>
                                   

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值