微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

asp.net 多文件上传,兼容IE6/7/8,提供完整代码下载

最终效果如下:


现贴出核心代码如下:
aspx里的代码

<div style="text-align: center">
<div style="width: 200px;">
<input type="file" size="50" name="File" />
<span id="upload"></span>
<br />
<input type="button" name="button" value="添加文件" onclick="addinput()">
<input type="button" name="button" value="删除文件" onclick="deleteinput()">
</div>
<div style="margin: 10px 0 10px 0;width: 200px;">
<asp:Button runat="server" Text="上传" ID="btnUpload" OnClick="btnUpload_Click"></asp:Button><br/>
<asp:Label ID="strStatus" runat="server"></asp:Label>
</div>
</div>

添加文件删除文件调用了Javascript,代码如下:


<script type="text/javascript">
var attachname = "uploadfile";
var i = 1;
function addinput() {
if (i > 0) {
var attach = attachname + i;
if (createInput(attach))
i = i + 1;
}
}
function deleteinput() {
if (i > 1) {
i = i - 1;
if (!removeinput())
i = i + 1;
}
}
function createInput(nm) {
var aElement = document.createElement("input");
aElement.name = nm;
aElement.id = nm;
aElement.type = "file";
aElement.size = "50";
if (document.getElementById("upload").appendChild(aElement) == null)
return false;
return true;
}
function removeInput(nm) {
var aElement = document.getElementById("upload");
if (aElement.removeChild(aElement.lastChild) == null)
return false;
return true;
}
</script>



后台响应保存文件的操作,保存文件关键的一句是要读取到文件列表,
//遍历File表单元素
HttpFileCollection files = HttpContext.Current.Request.Files;
上传以后保存文件代码如下:

protected void btnUpload_Click(object sender,EventArgs e)
{
//遍历File表单元素
HttpFileCollection files = HttpContext.Current.Request.Files;
System.Text.StringBuilder strMsg = new StringBuilder("<br/>");
strMsg.Append("上传文件分别是:</br>");
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/>");
strMsg.Append("上传文件的大小:" + postedFile.ContentLength + "<br/>");
//可扩展功能
//保存文件时可以设置保存目录
//可以重命名文件保存
postedFile.SaveAs(System.Web.HttpContext.Current.Request.MapPath("images/") + fileName);
}
}
strStatus.Text = strMsg.ToString();
}
catch (System.Exception Ex)
{
strStatus.Text = Ex.Message;
}
}


完整代码下载

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐