多图片上传+图片预览,兼容所有浏览器 IE5/IE6/IE7/IE8/IE9/Chrome/Safari/Firefox/Opera/
本文提供了一种实现多文件上传的方法,如果是图片上传,则支持图片文件的预览,兼容所有的常用浏览器,代码简单。但是,需要注意的是:本方法可能会产生一点点垃圾文件,如果对此比较在意的话,可以把图片路径存入数据库,在“完成上载”的按钮里面,删除保存的文件,对于数据库没有删除的,则可以定期进行删除处理,这样就不会有垃圾文件的存在了。完整的源代码如下,直接拷贝即可运行:
MultiFileUpload.aspx 代码 <%@ Page Language="C#" AutoEventWireup="true" CodeFile="MultiFileUpload.aspx.cs"Inherits="MultiFileUplaod" %>
<!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>
</head>
<body>
<form id="form1" runat="server">
<asp:HiddenField ID="allFileSize" runat="server" Value="0" />
<table>
<tr>
<td align="right">
本地文件:
</td>
<td>
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="btnAdd" runat="server" Text="添加文件" OnClick="btnAdd_Click" />
</td>
</tr>
<tr style="vertical-align:top">
<td align="right">
文件列表:
</td>
<td>
<asp:ListBox ID="lbxFile" runat="server" Height="145px" Width="245px" CssClass="txt">
</asp:ListBox>
<img alt="" src="" style="width: 100px; height: 100px; display: none;float:right" id="pre"runat="server" />
</td>
</tr>
<tr>
<td align="right">
预览:
</td>
<td id="x" runat="server">
</td>
</tr>
<tr>
<td colspan="2" style="text-align: center">
<asp:Button ID="btnDelete" runat="server" Text="删除文件" OnClick="btnDelete_Click"/>
<asp:Button ID="btnPost" runat="server" Text="完成上传" OnClick="btnPost_Click" />
</td>
</tr>
</table>
</form>
</body>
</html>
MultiFileUpload.aspx.cs C# 代码 using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections;
using System.IO;
public partial class MultiFileUplaod : System.Web.UI.Page
{
private String folder;
private String url;
protected void Page_Load(object sender, EventArgs e)
{
folder = Server.MapPath("~/temp");
if (!Directory.Exists(folder))
Directory.CreateDirectory(folder);
lbxFile.Attributes.Add("onchange", "document.getElementById('" + pre.ClientID +"').style.display='';document.getElementById('" + pre.ClientID + "').src=this.value.split('//|')[0]");
}
protected void btnAdd_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
String guid = Guid.NewGuid().ToString();
String newFileName = folder + "//" + guid + Path.GetExtension(FileUpload1.FileName);
url = Page.ResolveUrl("~") + "temp/" + guid + Path.GetExtension(FileUpload1.FileName);
int totalFileSize = Int32.Parse(allFileSize.Value);
int fileSize = FileUpload1.PostedFile.ContentLength;
//此处也可以限制单个文件的大小
if (totalFileSize + fileSize > 1024 * 1024 * 100)
{
Page.ClientScript.RegisterClientScriptBlock(typeof(string), "", @"<script>alert('总上传的文件超过了大小设置 1024 * 1024 !')</script>");
return;
}
FileUpload1.SaveAs(newFileName);
ListItem item = new ListItem();
item.Text = FileUpload1.FileName;
item.Value = url + "|" + newFileName;
for (int i = 0; i < lbxFile.Items.Count; i++)
{
if (lbxFile.Items[i].Text.Equals(FileUpload1.FileName, StringComparison.InvariantCultureIgnoreCase))
{
Page.ClientScript.RegisterClientScriptBlock(typeof(string), "", @"<script>alert('不能添加已经添加过的文件!')</script>");
return;
}
}
pre.Style["display"] = "";
pre.Src = url;
totalFileSize += fileSize;
allFileSize.Value = totalFileSize.ToString();
lbxFile.Items.Add(item);
PreViewImage();
}
}
protected void btnPost_Click(object sender, EventArgs e)
{
//对上传的文件进行进一步处理,或者退出弹出窗口等操作
for (int i = lbxFile.Items.Count - 1; i > -1; i--)
{
lbxFile.Items.Remove(lbxFile.Items[i]);
}
Page.ClientScript.RegisterClientScriptBlock(typeof(string), "", @"<script>alert('上传成功!')</script>");
}
protected void btnDelete_Click(object sender, EventArgs e)
{
for (int i = lbxFile.Items.Count - 1; i > -1; i--)
{
if (lbxFile.Items[i].Selected)
{
String value = lbxFile.Items[i].Value;
lbxFile.Items.Remove(lbxFile.Items[i]);
if (File.Exists(value.Split('|')[1]))
{
File.Delete(value.Split('|')[1]);
}
}
}
PreViewImage();
pre.Src = "";
pre.Style["display"] = "none";
}
private void PreViewImage()
{
String p = "";
for (int i = 0; i < lbxFile.Items.Count; i++)
{
p += "<img src='" + lbxFile.Items[i].Value.Split('|')[0] + "' style='width:100px;height:100px'>";
}
x.InnerHtml = p;
}
}
另外,可以添加一个新的功能,在选择完毕文件后就立即上传,无需点击上传按钮,具体的代码是在Page_Load里面加上 FileUpload1.Attributes.Add("onchange", "document.getElementById('" + btnAdd .ClientID+ "').click();"); 一行代码即可。
VB.NET版本(要注意AutoEventWireup="true"的设置与Handles Me.Load的使用,否则,事件可能不执行。)
VB.NET 代码 Imports System.Collections.GenericImports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Collections
Imports System.IO
Partial Class MultiFileUpload
Inherits System.Web.UI.Page
Private folder As String
Private url As String
Private Const SplitChar As Char = "|"c
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
folder = Server.MapPath("~/temp")
If Not Directory.Exists(folder) Then
Directory.CreateDirectory(folder)
End If
lbxFile.Attributes.Add("onchange", ("document.getElementById('" + pre.ClientID +"').style.display='';document.getElementById('") + pre.ClientID + "').src=this.value.split('/|')[0]")
End Sub
Protected Sub btnAdd_Click(ByVal sender As Object, ByVal e As EventArgs)
If FileUpload1.HasFile Then
Dim g As String = Guid.NewGuid().ToString()
Dim newFileName As String = folder + "/" + g + Path.GetExtension(FileUpload1.FileName)
url = Page.ResolveUrl("~") & "temp/" & g & Path.GetExtension(FileUpload1.FileName)
Dim totalFileSize As Integer = Int32.Parse(allFileSize.Value)
Dim fileSize As Integer = FileUpload1.PostedFile.ContentLength
'此处也可以限制单个文件的大小
If totalFileSize + fileSize > 1024 * 1024 * 100 Then
Page.ClientScript.RegisterClientScriptBlock(GetType(Page), "", "<script>alert('总上传的文件超过了大小设置 1024 * 1024 !')</script>")
Return
End If
FileUpload1.SaveAs(newFileName)
Dim item As New ListItem()
item.Text = FileUpload1.FileName
item.Value = url & "|" & newFileName
For i As Integer = 0 To lbxFile.Items.Count - 1
If lbxFile.Items(i).Text.Equals(FileUpload1.FileName, StringComparison.InvariantCultureIgnoreCase) Then
Page.ClientScript.RegisterClientScriptBlock(GetType(Page), "", "<script>alert('不能添加已经添加过的文件!')</script>")
Return
End If
Next
pre.Style("display") = ""
pre.Src = url
totalFileSize += fileSize
allFileSize.Value = totalFileSize.ToString()
lbxFile.Items.Add(item)
PreViewImage()
End If
End Sub
Protected Sub btnPost_Click(ByVal sender As Object, ByVal e As EventArgs)
'对上传的文件进行进一步处理,或者退出弹出窗口等操作
For i As Integer = lbxFile.Items.Count - 1 To 0 Step -1
lbxFile.Items.Remove(lbxFile.Items(i))
Next
Page.ClientScript.RegisterClientScriptBlock(GetType(Page), "", "<script>alert('上传成功!')</script>")
End Sub
Protected Sub btnDelete_Click(ByVal sender As Object, ByVal e As EventArgs)
For i As Integer = lbxFile.Items.Count - 1 To 0 Step -1
If lbxFile.Items(i).Selected Then
Dim value As String = lbxFile.Items(i).Value
lbxFile.Items.Remove(lbxFile.Items(i))
If File.Exists(value.Split(SplitChar)(1)) Then
File.Delete(value.Split(SplitChar)(1))
End If
End If
Next
PreViewImage()
pre.Src = ""
pre.Style("display") = "none"
End Sub
Private Sub PreViewImage()
Dim p As String = ""
For i As Integer = 0 To lbxFile.Items.Count - 1
p += "<img src='" + lbxFile.Items(i).Value.Split(SplitChar)(0) & "' style='width:100px;height:100px'>"
Next
x.InnerHtml = p
End Sub
End Class