一、单文件上传
#---后台代码
二、多文件(批量)上传
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Upload2.aspx.cs" Inherits="Upload2" %>
<!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>多文件上传_www.jb200.com</title>
<script language="javascript">
function addFile()
{
var str = '<INPUT type="file" size="50" NAME="File">'
document.getElementById('MyFile').insertAdjacentHTML("beforeEnd",str)
}
function AddRow()
{
// 表格的总行数
var rowCount = upLoadTable.rows.length;
// 添加行
var newTr = upLoadTable.insertRow();
// 设置 id 属性
var id = "Row" + rowCount.toString();
newTr.setAttribute("id",id);
// 添加列
var newTd0 = newTr.insertCell();
// 设置列内容和属性,并且加上删除行方法
newTd0.innerHTML = "<input type="file" size="50" name="File"><input type="button" value="删除" onClick="DelRow(this.parentElement.parentElement.rowIndex);"/>";
}
function DelRow(index)
{
upLoadTable.deleteRow(index);
}
</script>
</head>
<body>
<form id="form1" method="post" runat="server" enctype="multipart/form-data">
<table id="upLoadTable" border="1" align="center" width="500px">
<tr id="Row1">
<td>
<input type="file" size="50" name="File"><input type="button" value="删除" onclick="DelRow(this.parentElement.parentElement.rowIndex);" />
</td>
</tr>
</table>
<p align="center">
<input type="button" value="增加(Add)" onclick="AddRow();">
<asp:Button runat="server" Text="上传" ID="Upload" OnClick="Upload_Click"></asp:Button>
<input onclick="this.form.reset()" type="button" value="重置(ReSet)">
</p>
</tr>
<p align="center">
<asp:Label ID="showMsg" runat="server" Font-Names="宋体" Font-Bold="True" Font-Size="9pt"
Width="500px" BorderStyle="None" BorderColor="White"></asp:Label>
</p>
</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 Upload2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Upload_Click(object sender, EventArgs e)
{
this.showMsg.Text =String.Empty;
string savePath = Server.MapPath("Upload"); // 上传路径
System.Web.HttpFileCollection files = System.Web.HttpContext.Current.Request.Files;
try
{
for (int i = 0; i < files.Count; i++)
{
HttpPostedFile file = files[i] as System.Web.HttpPostedFile;
if (file != null && file.ContentLength != 0)
{
file.SaveAs(Path.Combine(savePath, Path.GetFileName(file.FileName)));
this.showMsg.Text += "文件 "+file.FileName + " 上传成功<br>";
}
}
}
catch(Exception ex)
{
this.showMsg.Text = ex.Message;
}
}
}
通过以上的学习,今后再处理c#文件上传的事情,应该问题不大了吧,祝你学习进步。