asp.net文件上传解决方案(图片上传、单文件上传、多文件上传、检查文件类型)
小编之前也介绍了许多ASP.NET文件上传的解决案例,今天来个asp.net文件上传大集合。
1使用标准HTML来进行图片上传
前台代码:
<body> <formid="form1"runat="server"> <div> <table> <tr> <tdcolspan="2"style="height:21px"> 使用标准HTML来进行图片上传</td> </tr> <tr> <tdstyle="width:400px"> <inputid="InputFile"style="width:399px"type="file"runat="server"/></td> <tdstyle="width:80px"> <asp:ButtonID="UploadButton"runat="server"Text="上传图片"OnClick="UploadButton_Click"/></td> </tr> <tr> <tdcolspan="2"> <asp:LabelID="Lb_Info"runat="server"ForeColor="Red"></asp:Label></td> </tr> </table> </div> </form> </body>
后台代码:
usingSystem;
usingSystem.Data;
usingSystem.Configuration;
usingSystem.Web;
usingSystem.Web.Security;
usingSystem.Web.UI;
usingSystem.Web.UI.WebControls;
usingSystem.Web.UI.WebControls.WebParts;
usingSystem.Web.UI.HtmlControls;
publicpartialclass_Default:System.Web.UI.Page
{
protectedvoidPage_Load(objectsender,EventArgse)
{
}
protectedvoidUploadButton_Click(objectsender,EventArgse)
{
stringuploadName=InputFile.Value;//获取待上传图片的完整路径,包括文件名
//stringuploadName=InputFile.PostedFile.FileName;
stringpictureName="";//上传后的图片名,以当前时间为文件名,确保文件名没有重复
if(InputFile.Value!="")
{
intidx=uploadName.LastIndexOf(".");
stringsuffix=uploadName.Substring(idx);//获得上传的图片的后缀名
pictureName=DateTime.Now.Ticks.ToString()+suffix;
}
try
{
if(uploadName!="")
{
stringpath=Server.MapPath("~/images/");
InputFile.PostedFile.SaveAs(path+pictureName);
}
}
catch(Exceptionex)
{
Response.Write(ex);
}
}
}
2单文件上传
这是最基本的文件上传,在asp.net1.x中没有这个FileUpload控件,只有html的上传控件,那时候要把html控件转化为服务器控件,很不好用。其实所有文件上传的美丽效果都是从这个FileUpload控件衍生,第一个例子虽然简单却是根本。
前台代码:
<body> <formid="form1"runat="server"> <div> <tablestyle="width:90%"> <tr> <tdstyle="width:159px"colspan=2> <strong><spanstyle="font-size:10pt">最简单的单文件上传</span></strong></td> </tr> <tr> <tdstyle="width:600px"> <asp:FileUploadID="FileUpload1"runat="server"Width="600px"/></td> <tdalign=left> <asp:ButtonID="FileUpload_Button"runat="server"Text="上传图片"OnClick="FileUpload_Button_Click"/></td> </tr> <tr> <tdcolspan=2> <asp:LabelID="Upload_info"runat="server"ForeColor="Red"Width="767px"></asp:Label></td> </tr> </table> </div> </form> </body>
后台代码:
usingSystem;
usingSystem.Data;
usingSystem.Configuration;
usingSystem.Web;
usingSystem.Web.Security;
usingSystem.Web.UI;
usingSystem.Web.UI.WebControls;
usingSystem.Web.UI.WebControls.WebParts;
usingSystem.Web.UI.HtmlControls;
publicpartialclass_Default:System.Web.UI.Page
{
protectedvoidPage_Load(objectsender,EventArgse)
{
}
protectedvoidFileUpload_Button_Click(objectsender,EventArgse)
{
try
{
if(FileUpload1.PostedFile.FileName=="")
//if(FileUpload1.FileName=="")
//if(!FileUpload1.HasFile)//获取一个值,该值指示System.Web.UI.WebControls.FileUpload控件是否包含文件。包含文件,则为true;否则为false。
{
this.Upload_info.Text="请选择上传文件!";
}
else
{
stringfilepath=FileUpload1.PostedFile.FileName;//得到的是文件的完整路径,包括文件名,如:C:\DocumentsandSettings\Administrator\MyDocuments\MyPictures\20022775_m.jpg
//stringfilepath=FileUpload1.FileName;//得到上传的文件名20022775_m.jpg
stringfilename=filepath.Substring(filepath.LastIndexOf("\\")+1);//20022775_m.jpg
stringserverpath=Server.MapPath("~/images/")+filename;//取得文件在服务器上保存的位置C:\Inetpub\wwwroot\WebSite1\images\20022775_m.jpg
FileUpload1.PostedFile.SaveAs(serverpath);//将上传的文件另存为
this.Upload_info.Text="上传成功!";
}
}
catch(Exceptionex)
{
this.Upload_info.Text="上传发生错误!原因是:"+ex.ToString();
}
}
}
3、多文件上传
前台代码:
<body> <formid="form1"runat="server"> <div> <tablestyle="width:343px"> <tr> <tdstyle="width:100px"> 多文件上传</td> <tdstyle="width:100px"> </td> </tr> <tr> <tdstyle="width:100px"> <asp:FileUploadID="FileUpload1"runat="server"Width="475px"/> </td> <tdstyle="width:100px"> </td> </tr> <tr> <tdstyle="width:100px"> <asp:FileUploadID="FileUpload2"runat="server"Width="475px"/></td> <tdstyle="width:100px"> </td> </tr> <tr> <tdstyle="width:100px"> <asp:FileUploadID="FileUpload3"runat="server"Width="475px"/></td> <tdstyle="width:100px"> </td> </tr> <tr> <tdstyle="width:100px"> <asp:ButtonID="bt_upload"runat="server"OnClick="bt_upload_Click"Text="一起上传"/> <asp:LabelID="lb_info"runat="server"ForeColor="Red"Width="448px"></asp:Label></td> <tdstyle="width:100px"> </td> </tr> </table> </div> </form> </body>
后台代码:
usingSystem;
usingSystem.Data;
usingSystem.Configuration;
usingSystem.Web;
usingSystem.Web.Security;
usingSystem.Web.UI;
usingSystem.Web.UI.WebControls;
usingSystem.Web.UI.WebControls.WebParts;
usingSystem.Web.UI.HtmlControls;
publicpartialclass_Default:System.Web.UI.Page
{
protectedvoidPage_Load(objectsender,EventArgse)
{
}
protectedvoidbt_upload_Click(objectsender,EventArgse)
{
if(FileUpload1.PostedFile.FileName==""&&FileUpload2.PostedFile.FileName==""&&FileUpload3.PostedFile.FileName=="")
{
this.lb_info.Text="请选择文件!";
}
else
{
HttpFileCollectionmyfiles=Request.Files;
for(inti=0;i<myfiles.Count;i++)
{
HttpPostedFilemypost=myfiles[i];
try
{
if(mypost.ContentLength>0)
{
stringfilepath=mypost.FileName;//C:\DocumentsandSettings\Administrator\MyDocuments\MyPictures\20022775_m.jpg
stringfilename=filepath.Substring(filepath.LastIndexOf("\\")+1);//20022775_m.jpg
stringserverpath=Server.MapPath("~/images/")+filename;//C:\Inetpub\wwwroot\WebSite2\images\20022775_m.jpg
mypost.SaveAs(serverpath);
this.lb_info.Text="上传成功!";
}
}
catch(Exceptionex)
{
this.lb_info.Text="上传发生错误!原因:"+ex.Message.ToString();
}
}
}
}
}
4、客户端检查上传文件类型(以上传图片为例)
<%@PageLanguage="C#"AutoEventWireup="true"CodeFile="Default.aspx.cs"Inherits="_Default"%>
<!DOCTYPEhtmlPUBLIC"-//W3C//DTDXHTML1.0Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<htmlxmlns="http://www.w3.org/1999/xhtml">
<headrunat="server">
<title>客户端检查上传文件类型</title>
<scriptlanguage="javascript">
functionCheck_FileType()
{
varstr=document.getElementById("FileUpload1").value;
varpos=str.lastIndexOf(".");
varlastname=str.substring(pos,str.length);
if(lastname.toLowerCase()!=".jpg"&&lastname.toLowerCase()!=".gif")
{
alert("您上传的文件类型为"+lastname+",图片必须为.jpg,.gif类型");
returnfalse;
}
else
{
returntrue;
}
}
</script>
</head>
<body>
<formid="form1"runat="server">
<div>
<table>
<tr>
<tdcolspan="2">
客户端检查上传文件类型</td>
</tr>
<tr>
<tdstyle="width:444px">
<asp:FileUploadID="FileUpload1"runat="server"Width="432px"/></td>
<tdstyle="width:80px">
<asp:ButtonID="bt_upload"runat="server"Text="上传图片"OnClick="bt_upload_Click"OnClientClick="returnCheck_FileType()"/></td>
</tr>
<tr>
<tdcolspan="2"style="height:21px">
<asp:LabelID="lb_info"runat="server"ForeColor="Red"Width="515px"></asp:Label></td>
</tr>
</table>
</div>
</form>
</body>
</html>
注意:点击上传时先触发客户端事件OnClientClick="returnCheck_FileType()"
usingSystem;
usingSystem.Data;
usingSystem.Configuration;
usingSystem.Web;
usingSystem.Web.Security;
usingSystem.Web.UI;
usingSystem.Web.UI.WebControls;
usingSystem.Web.UI.WebControls.WebParts;
usingSystem.Web.UI.HtmlControls;
publicpartialclass_Default:System.Web.UI.Page
{
protectedvoidPage_Load(objectsender,EventArgse)
{
}
protectedvoidbt_upload_Click(objectsender,EventArgse)
{
try
{
if(FileUpload1.PostedFile.FileName=="")
{
this.lb_info.Text="请选择文件!";
}
else
{
stringfilepath=FileUpload1.PostedFile.FileName;
//if(!IsAllowedExtension(FileUpload1))
//{
//this.lb_info.Text="上传文件格式不正确!";
//}
if(IsAllowedExtension(FileUpload1)==true)
{
stringfilename=filepath.Substring(filepath.LastIndexOf("\\")+1);
stringserverpath=Server.MapPath("~/images/")+filename;
FileUpload1.PostedFile.SaveAs(serverpath);
this.lb_info.Text="上传成功!";
}
else
{
this.lb_info.Text="请上传图片!";
}
}
}
catch(Exceptionex)
{
this.lb_info.Text="上传发生错误!原因:"+ex.ToString();
}
}
privatestaticboolIsAllowedExtension(FileUploadupfile)
{
stringstrOldFilePath="";
stringstrExtension="";
string[]arrExtension={".gif",".jpg",".bmp",".png"};
if(upfile.PostedFile.FileName!=string.Empty)
{
strOldFilePath=upfile.PostedFile.FileName;//获得文件的完整路径名
strExtension=strOldFilePath.Substring(strOldFilePath.LastIndexOf("."));//获得文件的扩展名,如:.jpg
for(inti=0;i<arrExtension.Length;i++)
{
if(strExtension.Equals(arrExtension[i]))
{
returntrue;
}
}
}
returnfalse;
}
}
注意:若去掉客户端的脚本和客户端事件OnClientClick="returnCheck_FileType()",在后台代码
改为:
if(!IsAllowedExtension(FileUpload1))
{
this.lb_info.Text="上传文件格式不正确!";
}
elseif(IsAllowedExtension(FileUpload1)==true)
即变成服务器端检查上传文件类型。
5、服务器端检查上传文件的类型(文件内部真正的格式)
<body> <formid="form1"runat="server"> <div> <table> <tr> <tdcolspan="2"> 服务器检查上传文件类型</td> </tr> <tr> <tdstyle="width:444px"> <asp:FileUploadID="FileUpload1"runat="server"Width="432px"/></td> <tdstyle="width:80px"> <asp:ButtonID="bt_upload"runat="server"Text="上传图片"OnClick="bt_upload_Click"/></td> </tr> <tr> <tdcolspan="2"style="height:21px"> <asp:LabelID="lb_info"runat="server"ForeColor="Red"Width="515px"></asp:Label></td> </tr> </table> </div> </form> </body>
后台代码:
usingSystem;
usingSystem.Data;
usingSystem.Configuration;
usingSystem.Web;
usingSystem.Web.Security;
usingSystem.Web.UI;
usingSystem.Web.UI.WebControls;
usingSystem.Web.UI.WebControls.WebParts;
usingSystem.Web.UI.HtmlControls;
usingSystem.IO;
publicpartialclass_Default:System.Web.UI.Page
{
protectedvoidPage_Load(objectsender,EventArgse)
{
}
protectedvoidbt_upload_Click(objectsender,EventArgse)
{
try
{
if(FileUpload1.PostedFile.FileName=="")
{
this.lb_info.Text="请选择文件!";
}
else
{
stringfilepath=FileUpload1.PostedFile.FileName;
if(IsAllowedExtension(FileUpload1)==true)
{
stringfilename=filepath.Substring(filepath.LastIndexOf("\\")+1);
stringserverpath=Server.MapPath("images/")+filename;
FileUpload1.PostedFile.SaveAs(serverpath);
this.lb_info.Text="上传成功!";
}
else
{
this.lb_info.Text="请上传图片";
}
}
}
catch(Exceptionerror)
{
this.lb_info.Text="上传发生错误!原因:"+error.ToString();
}
}
privatestaticboolIsAllowedExtension(FileUploadupfile)
{
FileStreamfs=newFileStream(upfile.PostedFile.FileName,FileMode.Open,FileAccess.Read);
BinaryReaderr=newBinaryReader(fs);
stringfileclass="";
bytebuffer;
try
{
buffer=r.ReadByte();
fileclass=buffer.ToString();
buffer=r.ReadByte();
fileclass+=buffer.ToString();
}
catch
{
}
r.Close();
fs.Close();
if(fileclass=="255216"||fileclass=="7173"||fileclass=="6677"||fileclass=="13780")//说明255216是jpg;7173是gif;6677是BMP,13780是PNG;7790是exe,8297是rar
{
returntrue;
}
else
{
returnfalse;
}
}
}
为大家推荐一个专题,供大家学习:《ASP.NET文件上传汇总》
是不是内容很精彩,喜欢的朋友就收藏起来吧,以后在遇到ASP.NET文件上传问题的时候能够有所帮助。