您的位置:首页 > 编程语言 > ASP

ASP.NET 使用HTML file控件进行文件上传

2014-04-01 15:57 405 查看
第一种:

<form id="form1"enctype="multipart/form-data" action="Default.aspx" method="post" >
<input type="button" value="添加附件" onclick="addAttachment()" />
<div id="divAttachment">
</div>
<input type="submit"  value="提交"/>
</form>


JS:

<script language="javascript">
function addAttachment() {
var div = document.createElement("div");
var input = document.createElement("input");
input.setAttribute("type", "file");
input.setAttribute("name", "file");
input.setAttribute("runat", "server");
input.setAttribute("size", "50");
div.appendChild(input);

var btnRemove = document.createElement("a");
btnRemove.setAttribute("href", "#");
btnRemove.innerText = "删除";
btnRemove.setAttribute("onclick", "removeAttachment(this)");
btnRemove.setAttribute("style", "text-decoration: none");
var span = document.createElement("span");
span.setAttribute("style", "padding-left: 5px");
span.appendChild(btnRemove);
div.appendChild(span);
document.getElementById("divAttachment").appendChild(div);
}
function removeAttachment(ctrl) {
while (ctrl.tagName != "DIV") {

ctrl = ctrl.parentNode;
}
ctrl.parentNode.removeChild(ctrl);
}

</script>


后台代码:

protected void Page_Load(object sender, EventArgs e)
{

if (!Page.IsPostBack) {
System.Web.HttpFileCollection files = Request.Files;

for (int fileCount = 0; fileCount < files.Count; fileCount++)
{

System.Web.HttpPostedFile postedfile = files[fileCount];
int size = postedfile.ContentLength;
if (size <= 8388608)
{
string fileName = System.IO.Path.GetFileName(postedfile.FileName);
if (!String.IsNullOrEmpty(fileName))
{

string fileExtension = System.IO.Path.GetExtension(fileName);    //获取文件类型

//上传目录
string directory = Server.MapPath("upload");
//文件全路径
string path = directory + "\\" + fileName;

//判断目录是否存在
if (!Directory.Exists(directory))
{
Directory.CreateDirectory(directory);
}
//文件存在就删除文件
if (File.Exists(path))
{
File.Delete(path);
}
//上传到服务器的路径

postedfile.SaveAs(path);
}
}
else if (size > 8388608)
{
Response.Write("<script>alert('上传文件不得超过8M');</script>");

}
}

}
}


第二种:

使用asp.net的服务器控件 BUTTON按钮进行提交

<form id="form1" runat="server"  enctype="multipart/form-data" action="Default.aspx" method="post" >

<input type="button" value="添加附件" onclick="addAttachment()" />
<div id="divAttachment">
</div>
<asp:Button runat="server" ID="button1" Text="提交" OnClick="sub_Fun" />
</form>


上面JS中去掉

input.setAttribute("runat", "server");
后台代码添加一个 public void sub_Fun(object sender, EventArgs e){}函数即可。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐