c#的aspx怎么进行上传操作 c#的aspx怎么进行上传操作能给我提供一个实例吗 解决方案 » 免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货 上传文件之全攻略:界面: 说明:附件右边的TextBox的ID为_FileDialogName,.”浏览”为HTML控件,”上传”为服务器控件,其HTML代码为:<TR> <TD height="30"> <DIV align="right">附件:</DIV> </TD> <TD> <asp:textbox id="_FileDialogName" runat="server" Width="144px" ReadOnly="True" CssClass="login_input"> </asp:textbox><INPUT id="UploadFile" onpropertychange="SetDialogFileName(this.value)" type="file" size="1" name="UploadFile" runat="server" style="WIDTH: 16px; HEIGHT: 22px" class="login_input"> <asp:Button id="btnUpload" runat="server" CssClass="login_input" Text="上 传"></asp:Button> <asp:Label id="lbmess" runat="server" ForeColor="Red"></asp:Label> </TD></TR>相信看完了这段代码之后,你肯定会发现,怎么有这个” SetDialogFileName(this.value)”东东,好的,先别急,待我再把它贴出来。function getFileType(str) { var sExtend = /([^.]+)$/.exec(str); return RegExp.$1; } function SetDialogFileName(s) { var sExt = getFileType(s).toUpperCase(); if (sExt == "BAT" || sExt == "EXE" || sExt == "COM"||sExt == "BIN"||sExt == "DLL" ||sExt == "CONFIG") { document.getElementById("_FileDialogName").value = ""; alert("非法文件类型!类型不能是.bat,.exe,.com,.bin,.dll"); } else { document.getElementById("_FileDialogName").value = s; } }看到这也许你就能恍然大悟了,原来是JS,用来检验上传的文件的格式。废话少说,我们把CS贴出来,个人觉得这段代码很清晰。protected System.Web.UI.WebControls.Button btnUpload;protected System.Web.UI.WebControls.TextBox _FileDialogName;protected System.Web.UI.HtmlControls.HtmlInputFile UploadFile;protected System.Web.UI.WebControls.Label lbmess;protected System.Web.UI.WebControls.LinkButton lbtnsave;private void btnUpload_Click(object sender, System.EventArgs e) { if(this._FileDialogName.Text.Length==0) { this.lbmess.Text="请先选择一个附件"; return; } long fileSize=this.UploadFile.PostedFile.ContentLength; if(fileSize>1024*1024*2) { this.lbmess.Text="文件不能大于2M"; this._FileDialogName.Text=""; return; } try { string extensionname=GetExtensionName(this._FileDialogName.Text);//文件扩展名 string filename=Guid.NewGuid().ToString()+"."+extensionname; string strPath = HttpContext.Current.Request.ApplicationPath //项目根路径 + System.Configuration.ConfigurationSettings.AppSettings["AttachFolder"] ; //上传文件的路径 if(ViewState["attachurl"]!=null&&ViewState["attachurl"].ToString().Length>36) { DeleteOldAttach(Server.MapPath(strPath+ViewState["attachurl"].ToString())); } strPath += filename; ViewState["attachurl"]=filename; this.UploadFile.PostedFile.SaveAs(Server.MapPath(strPath)); this.lbmess.Text="上传成功"; } catch { } } void DeleteOldAttach(string path) { try { System.IO.FileInfo fi=new System.IO.FileInfo(path); if(fi.Exists) fi.Delete(); } catch {} } private string GetExtensionName(string filepath) { int index=filepath.LastIndexOf("."); return filepath.Substring(index+1); }读者看完之后,相信应该可以很轻松读懂这段代码,需要说明的是上传文件的路径,在Web.Config设置如下: /// <summary> /// 上传文件--返回保存的文件名 /// </summary> private string UpFile() { //FileUpload为Html的文件上传控件 HttpPostedFile hpf=FileUpload.PostedFile; char[] sep={'\\'}; string[] AFileName=hpf.FileName.Split(sep); string GetFileName=AFileName[AFileName.Length-1]; string ServerPath=Server.MapPath(@".\UpFiles\"); if(!Directory.Exists(ServerPath)) { Directory.CreateDirectory(ServerPath); } string RFileName=DateTime.Now.ToString("yyyyMMddHHmmss")+GetFileName; string path=ServerPath+RFileName; hpf.SaveAs(path); return RFileName; } UpLoad.aspx<%@ Page language="c#" Codebehind="UpLoad.aspx.cs" AutoEventWireup="false" Inherits="WebPortal.Upload" %><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" ><HTML> <HEAD> <title>多文件上传</title> <script language="JavaScript"> function addFile() { var str = '<INPUT type="file" size="50" NAME="File">' document.getElementById('MyFile').insertAdjacentHTML("beforeEnd",str) } </script> </HEAD> <body> <form id="form1" method="post" runat="server" enctype="multipart/form-data"> <div align="center"> <h3>多文件上传</h3> <P id="MyFile"><INPUT type="file" size="50" NAME="File"></P> <P> <input type="button" value="增加(Add)" onclick="addFile()"> <input onclick="this.form.reset()" type="button" value="重置(ReSet)"> <asp:Button Runat="server" Text="开始上传" ID="UploadButton"></asp:Button> </P> <P> <asp:Label id="strStatus" runat="server" Font-Names="宋体" Font-Bold="True" Font-Size="9pt" Width="500px" BorderStyle="None" BorderColor="White"></asp:Label> </P> </div> </form> </body></HTML>UpLoad.aspx.csusing System;using System.Collections;using System.ComponentModel;using System.Data;using System.Drawing;using System.Web;using System.Web.SessionState;using System.Web.UI;using System.Web.UI.WebControls;using System.Web.UI.HtmlControls;namespace WebPortal{ /// <summary> /// UpLoad 的摘要说明。 /// 实现多文件上传 /// </summary> public class Upload : System.Web.UI.Page { protected System.Web.UI.WebControls.Button UploadButton; protected System.Web.UI.WebControls.Label strStatus; private void Page_Load(object sender, System.EventArgs e) { /// 在此处放置用户代码以初始化页面 if (this.IsPostBack) this.SaveImages(); } private Boolean SaveImages() { ///'遍历File表单元素 HttpFileCollection files = HttpContext.Current.Request.Files; /// '状态信息 System.Text.StringBuilder strMsg = new System.Text.StringBuilder(); strMsg.Append("上传的文件分别是:<hr color=red>"); 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><hr>"); ///'可根据扩展名字的不同保存到不同的文件夹 ///注意:可能要修改你的文件夹的匿名写入权限。 postedFile.SaveAs(System.Web.HttpContext.Current.Request.MapPath("images/") + fileName); } } strStatus.Text = strMsg.ToString(); return true; } catch(System.Exception Ex) { strStatus.Text = Ex.Message; return false; } } #region Web 窗体设计器生成的代码 override protected void OnInit(EventArgs e) { // // CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。 // InitializeComponent(); base.OnInit(e); } /// <summary> /// 设计器支持所需的方法 - 不要使用代码编辑器修改 /// 此方法的内容。 /// </summary> private void InitializeComponent() { this.ID = "Upload"; this.Load += new System.EventHandler(this.Page_Load); } #endregion }} 怎么就成这样呢?不好意思,我重发一次:UpLoad.aspx <%@ Page language="c#" Codebehind="UpLoad.aspx.cs" AutoEventWireup="false" Inherits="WebPortal.Upload" %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" > <HTML> <HEAD> <title>多文件上传</title> <script language="JavaScript"> function addFile() { var str = '<INPUT type="file" size="50" NAME="File">' document.getElementById('MyFile').insertAdjacentHTML("beforeEnd",str) } </script> </HEAD> <body> <form id="form1" method="post" runat="server" enctype="multipart/form-data"> <div align="center"> <h3>多文件上传</h3> <P id="MyFile"><INPUT type="file" size="50" NAME="File"></P> <P> <input type="button" value="增加(Add)" onclick="addFile()"> <input onclick="this.form.reset()" type="button" value="重置(ReSet)"> <asp:Button Runat="server" Text="开始上传" ID="UploadButton"></asp:Button> </P> <P> <asp:Label id="strStatus" runat="server" Font-Names="宋体" Font-Bold="True" Font-Size="9pt" Width="500px" BorderStyle="None" BorderColor="White"></asp:Label> </P> </div> </form> </body> </HTML> UpLoad.aspx.cs using System; using System.Collections; using System.ComponentModel; using System.Data; using System.Drawing; using System.Web; using System.Web.SessionState; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.HtmlControls; namespace WebPortal { /// <summary> /// UpLoad 的摘要说明。 /// 实现多文件上传 /// </summary> public class Upload : System.Web.UI.Page { protected System.Web.UI.WebControls.Button UploadButton; protected System.Web.UI.WebControls.Label strStatus; private void Page_Load(o b j e c t sender, System.EventArgs e) { /// 在此处放置用户代码以初始化页面 if (this.IsPostBack) this.SaveImages(); } private Boolean SaveImages() { ///'遍历File表单元素 HttpFileCollection files = HttpContext.Current.Request.Files; /// '状态信息 System.Text.StringBuilder strMsg = new System.Text.StringBuilder(); strMsg.Append("上传的文件分别是:<hr color=red>"); 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><hr>"); ///'可根据扩展名字的不同保存到不同的文件夹 ///注意:可能要修改你的文件夹的匿名写入权限。 postedFile.SaveAs(System.Web.HttpContext.Current.Request.MapPath("images/") + fileName); } } strStatus.Text = strMsg.ToString(); return true; } catch(System.Exception Ex) { strStatus.Text = Ex.Message; return false; } } #region Web 窗体设计器生成的代码 override protected void OnInit(EventArgs e) { // // CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。 // InitializeComponent(); base.OnInit(e); } /// <summary> /// 设计器支持所需的方法 - 不要使用代码编辑器修改 /// 此方法的内容。 /// </summary> private void InitializeComponent() { this.ID = "Upload"; this.Load += new System.EventHandler(this.Page_Load); } #endregion } } 汗。。这么多源代码你直接用那个upfile控件就可以了那个控件有个方法saveas("你的文件路径") moss 大虾进 谢谢 大虾帮我 求救 Response.Write("/// <summary>aa");想输出“/// <summary>aa”可是“<summary>”怎么没有输出啊 C# asp.net 操作word 异常 试图读取或者写入受保护的内存 急,在線朋友幫個忙! 關於'Web.Global' 在許多位置都已定義 怎么解決 奇怪的Access数据库insert问题! 应该是联动问题 如果实现查询 简单问问题,在线求救!看在美女的面上帮个忙吧! 讨论:我用哪一种授权方案好 菜鸟问题:关于查询窗体如何传到新的窗口? 控件问题???????
界面:
说明:附件右边的TextBox的ID为_FileDialogName,.”浏览”为HTML控件,”上传”为服务器控件,其HTML代码为:
<TR>
<TD height="30">
<DIV align="right">附件:</DIV>
</TD>
<TD>
<asp:textbox id="_FileDialogName" runat="server" Width="144px" ReadOnly="True" CssClass="login_input">
</asp:textbox><INPUT id="UploadFile" onpropertychange="SetDialogFileName(this.value)" type="file" size="1"
name="UploadFile" runat="server" style="WIDTH: 16px; HEIGHT: 22px" class="login_input">
<asp:Button id="btnUpload" runat="server" CssClass="login_input" Text="上 传"></asp:Button>
<asp:Label id="lbmess" runat="server" ForeColor="Red"></asp:Label>
</TD>
</TR>相信看完了这段代码之后,你肯定会发现,怎么有这个” SetDialogFileName(this.value)”东东,好的,先别急,待我再把它贴出来。
function getFileType(str)
{
var sExtend = /([^.]+)$/.exec(str);
return RegExp.$1;
}
function SetDialogFileName(s)
{
var sExt = getFileType(s).toUpperCase();
if (sExt == "BAT" || sExt == "EXE" || sExt == "COM"||sExt == "BIN"||sExt == "DLL" ||sExt == "CONFIG")
{
document.getElementById("_FileDialogName").value = "";
alert("非法文件类型!类型不能是.bat,.exe,.com,.bin,.dll");
}
else
{
document.getElementById("_FileDialogName").value = s;
}
}看到这也许你就能恍然大悟了,原来是JS,用来检验上传的文件的格式。废话少说,我们把CS贴出来,个人觉得这段代码很清晰。
protected System.Web.UI.WebControls.Button btnUpload;
protected System.Web.UI.WebControls.TextBox _FileDialogName;
protected System.Web.UI.HtmlControls.HtmlInputFile UploadFile;
protected System.Web.UI.WebControls.Label lbmess;
protected System.Web.UI.WebControls.LinkButton lbtnsave;
private void btnUpload_Click(object sender, System.EventArgs e)
{
if(this._FileDialogName.Text.Length==0)
{
this.lbmess.Text="请先选择一个附件";
return;
}
long fileSize=this.UploadFile.PostedFile.ContentLength;
if(fileSize>1024*1024*2)
{
this.lbmess.Text="文件不能大于2M";
this._FileDialogName.Text="";
return;
}
try
{
string extensionname=GetExtensionName(this._FileDialogName.Text);//文件扩展名
string filename=Guid.NewGuid().ToString()+"."+extensionname;
string strPath = HttpContext.Current.Request.ApplicationPath //项目根路径
+ System.Configuration.ConfigurationSettings.AppSettings["AttachFolder"] ; //上传文件的路径
if(ViewState["attachurl"]!=null&&ViewState["attachurl"].ToString().Length>36)
{
DeleteOldAttach(Server.MapPath(strPath+ViewState["attachurl"].ToString()));
}
strPath += filename;
ViewState["attachurl"]=filename;
this.UploadFile.PostedFile.SaveAs(Server.MapPath(strPath));
this.lbmess.Text="上传成功";
}
catch
{
} }
void DeleteOldAttach(string path)
{
try
{
System.IO.FileInfo fi=new System.IO.FileInfo(path);
if(fi.Exists)
fi.Delete();
}
catch
{}
}
private string GetExtensionName(string filepath)
{
int index=filepath.LastIndexOf(".");
return filepath.Substring(index+1);
}
读者看完之后,相信应该可以很轻松读懂这段代码,需要说明的是上传文件的路径,在Web.Config设置如下:
/// 上传文件--返回保存的文件名
/// </summary>
private string UpFile()
{
//FileUpload为Html的文件上传控件
HttpPostedFile hpf=FileUpload.PostedFile;
char[] sep={'\\'};
string[] AFileName=hpf.FileName.Split(sep);
string GetFileName=AFileName[AFileName.Length-1];
string ServerPath=Server.MapPath(@".\UpFiles\");
if(!Directory.Exists(ServerPath))
{
Directory.CreateDirectory(ServerPath);
} string RFileName=DateTime.Now.ToString("yyyyMMddHHmmss")+GetFileName;
string path=ServerPath+RFileName;
hpf.SaveAs(path); return RFileName;
}
UpLoad.aspx.csusing System;using System.Collections;using System.ComponentModel;using System.Data;using System.Drawing;using System.Web;using System.Web.SessionState;using System.Web.UI;using System.Web.UI.WebControls;using System.Web.UI.HtmlControls;namespace WebPortal{ /// <summary> /// UpLoad 的摘要说明。 /// 实现多文件上传 /// </summary> public class Upload : System.Web.UI.Page { protected System.Web.UI.WebControls.Button UploadButton; protected System.Web.UI.WebControls.Label strStatus; private void Page_Load(object sender, System.EventArgs e) { /// 在此处放置用户代码以初始化页面 if (this.IsPostBack) this.SaveImages(); } private Boolean SaveImages() { ///'遍历File表单元素 HttpFileCollection files = HttpContext.Current.Request.Files; /// '状态信息 System.Text.StringBuilder strMsg = new System.Text.StringBuilder(); strMsg.Append("上传的文件分别是:<hr color=red>"); 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><hr>"); ///'可根据扩展名字的不同保存到不同的文件夹 ///注意:可能要修改你的文件夹的匿名写入权限。 postedFile.SaveAs(System.Web.HttpContext.Current.Request.MapPath("images/") + fileName); } } strStatus.Text = strMsg.ToString(); return true; } catch(System.Exception Ex) { strStatus.Text = Ex.Message; return false; } } #region Web 窗体设计器生成的代码 override protected void OnInit(EventArgs e) { // // CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。 // InitializeComponent(); base.OnInit(e); } /// <summary> /// 设计器支持所需的方法 - 不要使用代码编辑器修改 /// 此方法的内容。 /// </summary> private void InitializeComponent() { this.ID = "Upload"; this.Load += new System.EventHandler(this.Page_Load); } #endregion }}
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
<HEAD>
<title>多文件上传</title>
<script language="JavaScript">
function addFile()
{
var str = '<INPUT type="file" size="50" NAME="File">'
document.getElementById('MyFile').insertAdjacentHTML("beforeEnd",str)
}
</script>
</HEAD>
<body>
<form id="form1" method="post" runat="server" enctype="multipart/form-data">
<div align="center">
<h3>多文件上传</h3>
<P id="MyFile"><INPUT type="file" size="50" NAME="File"></P>
<P>
<input type="button" value="增加(Add)" onclick="addFile()">
<input onclick="this.form.reset()" type="button" value="重置(ReSet)">
<asp:Button Runat="server" Text="开始上传" ID="UploadButton"></asp:Button>
</P>
<P>
<asp:Label id="strStatus" runat="server" Font-Names="宋体" Font-Bold="True" Font-Size="9pt"
Width="500px" BorderStyle="None" BorderColor="White"></asp:Label>
</P>
</div>
</form>
</body>
</HTML> UpLoad.aspx.cs using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls; namespace WebPortal
{
/// <summary>
/// UpLoad 的摘要说明。
/// 实现多文件上传
/// </summary>
public class Upload : System.Web.UI.Page
{
protected System.Web.UI.WebControls.Button UploadButton;
protected System.Web.UI.WebControls.Label strStatus; private void Page_Load(o b j e c t sender, System.EventArgs e)
{
/// 在此处放置用户代码以初始化页面
if (this.IsPostBack) this.SaveImages();
} private Boolean SaveImages()
{
///'遍历File表单元素
HttpFileCollection files = HttpContext.Current.Request.Files; /// '状态信息
System.Text.StringBuilder strMsg = new System.Text.StringBuilder();
strMsg.Append("上传的文件分别是:<hr color=red>");
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><hr>");
///'可根据扩展名字的不同保存到不同的文件夹
///注意:可能要修改你的文件夹的匿名写入权限。
postedFile.SaveAs(System.Web.HttpContext.Current.Request.MapPath("images/") + fileName);
}
}
strStatus.Text = strMsg.ToString();
return true;
}
catch(System.Exception Ex)
{
strStatus.Text = Ex.Message;
return false;
}
}
#region Web 窗体设计器生成的代码
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。
//
InitializeComponent();
base.OnInit(e);
} /// <summary>
/// 设计器支持所需的方法 - 不要使用代码编辑器修改
/// 此方法的内容。
/// </summary>
private void InitializeComponent()
{
this.ID = "Upload";
this.Load += new System.EventHandler(this.Page_Load); }
#endregion
}
}