在做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=" 300px"/>描述:<input name="text" type="text" style=" 150px" maxlength="20" />'
document.getElementById('MyFile').insertAdjacentHTML("beforeEnd",str)
}
else
{
alert("您一次最多只能上传8张图片!")
}
i++
}
</script>
var i=1
function addFile()
{
if (i<8)
{var str = '<BR> <input type="file" name="File" runat="server" style=" 300px"/>描述:<input name="text" type="text" style=" 150px" maxlength="20" />'
document.getElementById('MyFile').insertAdjacentHTML("beforeEnd",str)
}
else
{
alert("您一次最多只能上传8张图片!")
}
i++
}
</script>
<P id="MyFile"><INPUT onclick="addFile()" type="button" value="增加图片(Add)"><br />
<input type="file" name="File" runat="server" style=" 300px"/>
描述:<input name="text" type="text" style=" 150px" maxlength="20" />
<input type="file" name="File" runat="server" style=" 300px"/>
描述:<input name="text" type="text" style=" 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)
{
.......................... //上传单个文件并保存相关信息
}
}
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=" 300px"/>描述:<input name="text" type="text" style=" 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">
</td>
</tr>
<tr>
<td align="center">
<asp:Panel ID="Panel5" runat="server" Width="608px">
<table width="100%">
<tr>
<td align="right" style=" 100px">
</td>
<td align="left">
说明:点增加图片按钮可一次上传多张图片,可为每张图片写上一句不超过20个字的描述。单张图片大小不大于1024k</td>
</tr>
<tr>
<td align="right" style=" 100px">
请选择图片:<br />
</td>
<td align="left"><P id="MyFile"><INPUT onclick="addFile()" type="button" value="增加图片(Add)"><br />
<input type="file" name="File" runat="server" style=" 300px"/>
描述:<input name="text" type="text" style=" 150px" maxlength="20" />
</td>
</tr>
<tr>
<td align="right" style=" 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=" 100px">
</td>
<td align="left">
<asp:Button ID="btnUpload" runat="server" Text="开始上传" OnClick="btnUpload_Click" />
</td>
</tr>
<tr>
<td align="right" style=" 100px">
</td>
<td align="left">
<asp:Label ID="lblMessage" runat="server" Font-Bold="True" ForeColor="Red"></asp:Label></td>
</tr>
</table>
</asp:Panel>
</td>
</tr>
<tr>
<td align="center">
<font face="宋体"></font><font face="宋体"> </font>
</td>
</tr>
<tr>
<td align="center">
<font face="宋体"></font>
</td>
</tr>
</table>
</div>
</form>
</body>
</html>
<!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=" 300px"/>描述:<input name="text" type="text" style=" 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">
</td>
</tr>
<tr>
<td align="center">
<asp:Panel ID="Panel5" runat="server" Width="608px">
<table width="100%">
<tr>
<td align="right" style=" 100px">
</td>
<td align="left">
说明:点增加图片按钮可一次上传多张图片,可为每张图片写上一句不超过20个字的描述。单张图片大小不大于1024k</td>
</tr>
<tr>
<td align="right" style=" 100px">
请选择图片:<br />
</td>
<td align="left"><P id="MyFile"><INPUT onclick="addFile()" type="button" value="增加图片(Add)"><br />
<input type="file" name="File" runat="server" style=" 300px"/>
描述:<input name="text" type="text" style=" 150px" maxlength="20" />
</td>
</tr>
<tr>
<td align="right" style=" 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=" 100px">
</td>
<td align="left">
<asp:Button ID="btnUpload" runat="server" Text="开始上传" OnClick="btnUpload_Click" />
</td>
</tr>
<tr>
<td align="right" style=" 100px">
</td>
<td align="left">
<asp:Label ID="lblMessage" runat="server" Font-Bold="True" ForeColor="Red"></asp:Label></td>
</tr>
</table>
</asp:Panel>
</td>
</tr>
<tr>
<td align="center">
<font face="宋体"></font><font face="宋体"> </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);
}
}
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);
}
}