您的位置:首页 > Web前端 > HTML

asp.net,C#,html控件的File控件文件上传简单实例,vs2010

2013-02-17 11:35 956 查看
文件上传是最常用的B/S项目功能,在FileUpload控件出来之前只能使用html控件的File控件,这样在form中就需要加入【 enctype="multipart/form-data"】。

实例如下,

up2.aspx代码

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="up2.aspx.cs" Inherits="up2" %>

<!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>
</head>
<body>
<form id="form1" runat="server" enctype="multipart/form-data">
<input name="File" type="file"  />
<asp:Button ID="Button1" runat="server" CssClass="button" OnClick="Button1_Click"
Text="上传" />
</form>
</body>
</html>


up2.aspx.cs代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using System.IO;

public partial class up2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}

protected void Button1_Click(object sender, EventArgs e)
{
string upPath = "/up/";  //上传文件路径
int upLength = 5;        //上传文件大小
string upFileExtName = "|bmp|jpg|jpeg|png|gif|";

HttpFileCollection _files = System.Web.HttpContext.Current.Request.Files;

for (int i = 0; i < _files.Count; i++)
{
string name = _files[i].FileName;

FileInfo fi = new FileInfo(name);

string oldfilename = fi.Name;
string scExtension = fi.Extension.ToLower();

string fileName = DateTime.Now.ToString("yyyyMMddhhmmssfff") + fi.Extension; // 文件名称,当前时间(yyyyMMddhhmmssfff)
string webFilePath = Server.MapPath(upPath) + fileName;        // 服务器端文件路径

if (upFileExtName.IndexOf(scExtension.Replace(".", "")) == -1)
{
ClientScript.RegisterStartupScript(this.GetType(), "upfileOK", "alert('提示:文件类型不符" + scExtension + "');", true);
return;
}

if ((fi.Length / (1024 * 1024)) > upLength)
{
ClientScript.RegisterStartupScript(this.GetType(), "upfileOK", "alert('大小超出 " + upLength + " M的限制,请处理后再上传!');", true);
return;
}

try
{
_files[i].SaveAs(webFilePath);

ClientScript.RegisterStartupScript(this.GetType(), "upfileOK", "alert('提示:文件上传成功');", true);
}
catch (Exception ex)
{
ClientScript.RegisterStartupScript(this.GetType(), "upfileOK", "alert('提示:文件上传失败" + ex.Message + "');", true);
}

}

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐