61阅读

asp文件上传-[ASP.NET] 限制上传文件类型的两种方法

发布时间:2017-10-20 所属栏目:asp.net网页制作

一 : [ASP.NET] 限制上传文件类型的两种方法

  通常,为了防止因用户上传有害文件(如木马、黑客程序)引发的安全性问题,Web程序都会对用户允许上传的文件类型加以限制。而本文将要介绍的就是如何在ASP.NET应用程序中利用Web Control的内置属性简单高效地实现限制上传文件类型的功能。

  在调用PostFile对象的SaveAs方法保存上传文件之前,可以通过PostFile对象的FileName属性得到上传的文件名。而有了上传的文件名,就可以采用比对文件后缀名的方法知道上传的文件是否属于允许上传的文件类型。

  根据这个思想,我们就得到了下面这段代码:

  If Path.GetExtension(sFilePath) <> ".zip" Then

  Label2.Text = "本应用程序只允许上传zip格式的文件,请重新选择!"

  Return

  这时如果上传后缀名不是zip的文件,就会发现文件无法上传了。不过,这并表示我们就不能把上传其他格式的文件了。其实,如果在上传前,事先把文件后缀名改成zip,上面这段代码就失去作用了。

  之所以会出现这种情况,在于上面的判断仅仅比对了文件名字符串,并没有对文件格式做进一步的分析。因此,如果要彻底限制上传的文件类型,还需要用到PostFile对象的ContentType属性。ContentType属性的功能是获取客户端发送的文件的 MIME (注一)内容类型,由于浏览器在向服务器发送请求前,首先会确定发送内容的MIME类型,并将MIME类型作为信息的一部分提交到服务器端,因此,有了MIME类型信息(注二),就可以准确知道上传文件的实际类型了。

  If File1.PostedFile.ContentType <> "application/zip" Then

  Label2.Text = "本应用程序只允许上传zip格式的文件,请重新选择!"

  这时,如果再采用修改后缀名的方法上传文件就会发现再也无法上传了。

  注一:MIME是一种技术规范,其中文翻译为多用途Internet邮件扩展(Multipurpose Internet Mail Extensions),主要用来在Internet传输过程中表示不同编码格式的文件;

  注二:要获取不同文件格式的MIME定义,只要启动注册表编辑器,然后在HKEY_CLASSES_ROOT下找到跟后缀名对应的注册表项,如果存在文件格式的MIME定义,在右侧窗口就会显示一个名为“Content Type”的键,而这个键的值就是文件格式的MIME定义。

  以上两种方法混用,上传文件基本上就被限制了。但是如果某些有心人如果更改注册表的 MIME 值的内容一样可以上传恶意程序,如果这样的话,只有加固程序和系统,不让其更改上传后文件的扩展名。或是采用自定义的控件,采用更严密的检测措施

二 : ASP文件上传方式大比拼

ASP文件上传方式大比拼

转]ASP文件上传方式大比拼



ASP文件上传方式大比拼
 

无组件方式
 

1.化境ASP无组件上传 V2.0;(下载)
  一直以来,由于FileSystemObject的局限,所以ASP最大的难题就是文件上传,大多解决法就是安装第三方上传组件。[www.61k.com]可第三方组件有很多问题,有的组件要注册,有的组件要在表单中加上他的版权信息。还有的就是组件的兼容问题。在网上也流传了很多无组件上传的代码,但都是只能上传文本文件,或是只能将文件上传到数据库中。 化境无组件上传的概念,是在全国,甚至整个网络界,首次提出的,由于代码是开发的,所以在本代码发布后,现在已被网友修改成各式各样的版本。 

2.无惧无组件上传类2.0;(下载)
  在2004年7月10日完成了"无惧无组件上传类2.0"版,该版相对于前作在安全上作出了最大的改进,在类内部实现了上传类型的黑白名单,更多方便了各种上传的环境,即使黑客突破了上传程序,但是最终在保存文件时会使他的所有努力付之流水,该版在使用上比前作更加方便,更人性化了。由于添加和修改了不少属性值,在移植上需要作出比较大的修改。 

3.风声无组件上传类V2.0 [Rumor UpLoadClass Version 2.0];(下载)
  长期以来,上传文件是ASP的一个难题。第三方组件上传速度快,但是需要在服务器端注册,而且有部分需要附加版权信息或付费使用,对大多数用户是可望不可及的事。网络上流传的一些无组件上传类,质量良莠不齐,在安全性设计上甚至存在一些漏洞,在性能方面,更是让用户望而却步。网标(Net Builder)经过长时间对上传算法的研究优化,开发出可与组件上传相媲美的ASP无组件上传类——风声无组件上传类。经测试,该无组件上传类在性能上明显超过同类ASP无组件上传程序,接近甚至超过一些上传组件,安全性、易用性更优于同类程序。 

组件方式1.LyfUpload上传组件(国产,作者:刘玉锋);(下载)
  国产的很好用的免费上传组件

支持单文件上传 (1.2版支持上载文件覆盖判断功能)

支持上传多个文件

可以将上传的文件改名保存(1.2版支持变量保存功能)

可以同时使用其它的form元素的信息

支持限制文件上传的大小

支持限制文件上传的类型 (1.1版修改,支持多文件类型)(1.2版修正)

可以得到上传文件的大小 (1.1版新增功能)

支持将文件内容保存进数据库,如上载图形文件、DOC文件等各类Windows文件 (1.1版新增功能)

支持从数据库中读取上载文件到数据库中的记录,如显示图形文件、DOC文件等各类Windows文件 (1.1版新增功能)

可以得到上传文件的MIME类型,如gif文件为images/gif(1.2版修正)

本版本完全免费,没有任何限制 

2.W3Upload上传组件;(下载)
  与W3Jmail同一师门,老牌的上传组件;

3.AspUpload3.0上传组件;(下载)
  邮件组件AspEmail大家肯定不陌生,这是同一家公司的产品,很不错的,支持进度条显示上传进度。

4.SaFileup上传组件;(下载)
  老牌上传组件 

5.SiteGalaxyUpload上传组件;(下载)
   老牌上传组件  

扩展:asp.net 上传文件 / asp.net mvc 上传文件 / asp上传文件代码

三 : asp.net+ajaxfileupload.js 实现文件异步上传代码分享

由于代码很简单,这里就闲话不多说了,直接上代码,小伙伴们自己研读代码就明白了。

前台代码:

代码如下:

/*修改头像*/

//上传

function _sc() {

$(".ckfile").html("").css("color", "#535353");

$("#_userImgPath").val("");

var str = $("#file").val();

if ($.trim(str) == "") {

$(".ckfile").html("请选择文件。").css("color", "red");

return false;

}

else {

var postfix = str.substring(str.lastIndexOf(".") + 1).toUpperCase();

if (postfix == "JPG" || postfix == "JPEG" || postfix == "PNG" || postfix == "GIF" || postfix == "BMP") {

$('#showimg').attr('src', 'Images/loading.gif').attr("title", "上传中,请稍后…");

var path = "Upload/UserImg";

$.ajaxFileUpload({

url: '/Upload.aspx?path=Upload|UserImg&shape=100*100',

secureuri: false,

fileElementId: 'file',

dataType: 'text',

success: function (msg) {

if (msg.lastIndexOf(path) == -1) {

$(".ckfile").html(msg).css("color", "red");

}

else {

$('#showimg').attr('src', msg).attr("title", "我的头像");

$("#_userImgPath").val(msg);

}

}

});

} else {

$(".ckfile").html("文件格式错误。").css("color", "red");

return false;

}

}

}

后台代码:

代码如下:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

using SS.Upload;

using WFC.Fenxiao;

namespace wanfangcheng

{

public partial class Upload : BasePage

{

//文件大小 1024 kb

private long size = 1024;

//文件类型

private string type = ".jpg|.jpeg|.png|.gif|.bmp";

//保存名称

string name = "";

//保存路径

private string path = @"Upload/UserImg";

//保存大小

private string shape = "100*100";

protected void Page_Load(object sender, EventArgs e)

{

HttpFileCollection files = Request.Files;

if (files != null && files.Count > 0)

{

name = BaseRole.Instance.UserId.ToString();

if (Request.QueryString["size"] != null)

{

size = Convert.ToInt32(Request.QueryString["size"]);

}

if (Request.QueryString["path"] != null)

{

path = Request.QueryString["path"].ToString().Trim().Replace('|', '/');

}

if (Request.QueryString["name"] != null)

{

name = Request.QueryString["name"].ToString().Trim();

}

if (Request.QueryString["shape"] != null)

{

shape = Request.QueryString["shape"].ToString().Trim();

}

uploadMethod(files);

}

}

/// <summary>

/// 上传图片

/// </summary>

/// <param name="hc"></param>

public void uploadMethod(HttpFileCollection hc)

{

HttpPostedFile _file = hc[0];

//文件大小

long _size = _file.ContentLength;

if (_size <= 0)

{

Response.Write("文件错误。");

Response.End();

return;

}

if (size * 1024 < _size)

{

Response.Write("文件过大,最大限制为" + size + "KB。");

Response.End();

return;

}

//文件名

string _name = _file.FileName;

//文件格式

string _tp = System.IO.Path.GetExtension(_name).ToLower();

if (type.IndexOf(_tp) == -1)

{

Response.Write("文件格式错误。");

Response.End();

return;

}

//保存路径

string _path = HttpContext.Current.Server.MapPath(path) + @"/" + name + _tp;

try

{

int w = Convert.ToInt32(shape.Split('*')[0]);

int h = Convert.ToInt32(shape.Split('*')[1]);

ImageHelper.CutForCustom(_file, _path, w, h, 50);

Response.Write(path + @"/" + name + _tp);

}

catch (Exception(www.61k.com])

{

Response.Write("哎呦,出错了。");

Response.End();

}

}

}

}

是不是很实用,也很简单易懂呢,以上是自己项目中使用的代码,小伙伴们如果发现有问题的地方,还请告之。谢谢

四 : asp利用文件上传组件upload_5xsoft文件上传

我们是利用upload文件上传组件进行文件上传哦。

<%Server.ScriptTimeOut=5000%>
<!--#include file="conn.asp"-->
<!--#include FILE="upload_5xsoft.inc"-->
<html>
<head>
<title>文件上传</title>
<link rel="stylesheet" href="<%=css%>" type="text/css">
<meta http-equiv="Content-Type" content="text/html; charset=gb2312"></head>
<body>
<%dim upload,file,formName,formPath,iCount,exeec,wjm
set upload=new upload_5xsoft
formPath="FJ/"

ly=upload.form("content")
yhm=upload.form("yhm")
zid=upload.form("zid")
ys=upload.form("ys")
yyzm = upload.form("yzm")
zt=upload.form("zt")
ztid=upload.form("ztid")
cz=upload.form("cz")
tp=upload.form("tp")
if tp = "http://" then tp = ""
ly=xrzh(ly)

if cz = "" then
fhlj = "bbs_list.asp?zid="&zid
else
fhlj = "bbs_tj.asp?page=1000&zt="&zt&"&ztid="&ztid&"&zid="&zid
zid = ztid
end if

if yyzm <> session(sessionvalue & "yzm") then redirect fhlj

zhhf = jdsj
if yhm = "" then yhm = "游客"''request.servervariables("remote_addr")

for each formName in upload.objFile ''列出所有上传了的文件
set file = upload.file(formName)
if file.FileSize>0 then
kzm = lcase(right(file.filename,4))
if instr(",.mpg.asf.avi.mp3.swf.mpeg.png.gif.bmp.jpg.wma.wmv.txt",kzm)<= 0 then response.Redirect hflj
if file.filesize > 819200 then%>
<script language="javascript">
alert("文件大于800k!");
window.location="<%=fhlj%>";
</script>
<%end if
wjdx = file.filesize
wjm = formpath&replace(cstr(date),"-","") & cstr(Replace(Timer(), ".", "")) & kzm
file.SaveAs Server.mappath(wjm)
dx = cstr(file.filesize/1024)
if len(dx) >6 then dx=left(dx,6)
end if
next
if trim(zt) <>"" then
sql = "select * from yrwl_tb_lt order by id desc"
set rs = server.createobject("adodb.recordset")
rs.open sql,conn,1,3
if sjk <> "" then
if rs.eof then
id = "1"
else
id = cstr(rs("id")+1)
end if
end if
rs.addnew
if sjk = "" then
if rs.eof then
id = "1"
else
id = cstr(rs("id"))
end if
end if
rs("yhm") = yhm

rs("zt") = zt
rs("ly") = ly

if wjm = "" and tp <> "" then wjm = tp
rs("fj") = wjm
rs("dx") = dx
rs("dj") = 0
rs("zd") = "5"
rs("hf") = 0
if cz = "" then
rs("zid") = "s"
rs("zhhf") = jdsj & " "&yhm
rs("lb") = zid
else
rs("zid") = zid
sql = "select * from yrwl_tb_lt where id=" & zid
set rs1 = server.createobject("adodb.recordset")
rs1.open sql,conn,1,3
rs1("zhhf") = jdsj & " "&yhm
rs1.update
rs1.close
end if

rs("sj") = jdsj
rs.update
rs.close

if instr(yhm,".") = 0 and yhm <> "游客" then
exec="select * from yrwl_tb_admin where yhm='"&yhm&"'"
rs.open exec,conn,3,3
cs = rs("cs")
qm = rs("qm")
if isnull(cs) then cs = 0
if cs="" then cs=0
exec="update yrwl_tb_admin set cs=" & cstr( cs + 3 ) & " where yhm='" & yhm & "'"
conn.execute exec
end if

if cz = "" then
''读文件
if wjm <> "" then
kzm = lcase(right(wjm,3))
if instr(wjm,"http") = 0 then wjm = "../" & wjm
xswjm = gqzh(wjm)
if len(wjm)>4 and instr(wjm,"FJ")>0 then
tpxs = xswjm & "<br>附件下载:<a href=" & wjm & " target=_blank>[" & wjm &"]</a>"
else
tpxs = xswjm
end if
if tpxs = "" or (instr(wjm,"swf")>0) then tpxs = "<iframe id=kj name=kj frameborder=0 width=100% height=500 src="&wjm&"></iframe>"
end if

set fso = Server.Createobject("Scripting.FileSystemObject")
set file=fso.opentextfile(Server.mappath("tbtb.txt"),1,False)
do while file.AtEndOfStream<>true
wjnr = wjnr & file.ReadLine() & chr(13)
loop
file.close
set file = nothing
set fso = nothing
if isnull(qm) then qm = ""
ly = replace(ly,chr(13),"<br>")
wjnr = replace(wjnr,"$ti$",zt)
wjnr = replace(wjnr,"$sj$",jdsj)
wjnr = replace(wjnr,"$zt$", kill_keyword(zt))
wjnr = replace(wjnr,"$ly$", kill_keyword(ly) & "<br>" & tpxs & "--------------------------------------<Br> 个性签名:<a title="&qm&">"&qm&"</a>")
wjnr = replace(wjnr,"$zid$",zid)
wjnr = replace(wjnr,"$qm$",qm)
wjnr = replace(wjnr,"$ztid$",id)

if instr(yhm,".")>0 then yhm=left(yhm,instrrev(yhm,"."))&"*"
wjnr = replace(wjnr,"$fyr$",yhm)
wjnr = replace(wjnr,"$lxfs$",session(sessionvalue & "lxfs"))
''写文件
wj = Server.mappath( "tb/" & id & ".htm" )
set myfileobject=server.CreateObject("Scripting.FileSystemObject")
set mytextfile=myfileobject.CreateTextFile(wj)
mytextfile.WriteLine wjnr
mytextfile.close
end if

set file=nothing
set upload=nothing ''删除此对象
end if
conn.close
response.redirect fhlj%>
</body>
</html>

五 : 摘录网络 asp 上传代码 支持大文件上传

<%@Language="VBScript"CodePage=65001%>

  <%OptionExplicit%>

  <%



  'Code:200(上传成功)、504(文件为空)、502(上传上限)、501(表示网络中断)、500(上传错误)、

  '505(文件类型禁止上传),506(未设置允许的文件后缀),507(未设置上传路径)

  '--------------------------------------------------------------------------------------

  '--------------------------------------------------------------------------------------

  Server.ScriptTimeout=99999999

  Response.Buffer=True

  Response.Charset="utf-8"

  ConstUPLOAD_PATH="/upload/"

  ClassUpload_Cls

  PrivateobjUpStream,objConvertStream,objFso

  PrivatelngMaxSize,lngRequestBytes,lngReadChunkBytes

  PrivatestrCode

  PrivatestrFileSuffix,strFilename,strAllowSuffix,strFilePath,lngFileSize,i



  PrivateSubClass_Initialize()

  Code=0

  MaxSize=0

  lngReadChunkBytes=131072'64KB

  lngRequestBytes=CLng(Request.TotalBytes)

  EndSub



  PrivateSubClass_Terminate()

  IfIsObject(objUpStream)Then

  objUpStream.Close

  SetobjUpStream=Nothing

  SetobjConvertStream=Nothing

  Endif

  EndSub



  '------

  '定义允许上传的文件格式,用英文逗号隔开(,)形如:gif,jpg

  '------

  PublicPropertyLetAllowSuffix(strVal)

  strAllowSuffix=LCase(strVal)

  EndProperty



  PublicPropertyGetFileName()

  FileName=strFileName

  EndProperty



  PublicPropertyLetFileName(strVal)

  strFileName=strVal

  EndProperty

  '------

  '获取上传的文件后缀名

  '------

  PublicPropertyGetFileSuffix()

  FileSuffix=strFileSuffix

  EndProperty



  PublicPropertyLetFileSuffix(strVal)

  strFileSuffix=strVal

  EndProperty



  '------

  '获取上传文件大小单位:KB

  '------

  PublicPropertyGetFileSize()

  FileSize=lngFileSize

  EndProperty



  PrivatePropertyLetFileSize(lngVal)

  lngFileSize=lngVal

  EndProperty



  '-------

  '获取上传文件相对路径

  '-------

  PublicPropertyGetFilePath()

  FilePath=strFilePath

  EndProperty



  '-------

  '设置上传文件路径

  '-------

  PublicSubSetFilePath(strCurpath,n)

  DimintRnd

  SelectCasen

  CaseElse

  Randomize

  intRnd=Int(9000*Rnd)

  Randomize

  intRnd=intRnd+Int(100*Rnd)

  strFilePath=strCurpath&FormatTimePattern(Now(),"ymd")&"/"

  EndSelect

  CallCreateFolder(Server.MapPath(FilePath))

  EndSub



  '------

  Rem根据时间生成的文件名

  '------

  PublicFunctionAutoFilePath()

  AutoFilePath=FilePath&FileName

  EndFunction



  PublicFunctionFormatTimePattern(dateSTime,strPattern)

  DimdateTime,strVal

  dateTime=dateSTime

  strVal=strPattern

  strVal=Replace(strVal,"y",Year(dateTime))

  strVal=Replace(strVal,"m",Fill0Char(Month(dateTime)))

  strVal=Replace(strVal,"d",Fill0Char(Day(dateTime)))

  strVal=Replace(strVal,"h",Fill0Char(Hour(dateTime)))

  strVal=Replace(strVal,"n",Fill0Char(Minute(dateTime)))

  strVal=Replace(strVal,"s",Fill0Char(Second(dateTime)))

  FormatTimePattern=strVal

  EndFunction



  PrivateFunctionFill0Char(strVal)

  IfLen(strVal)<2Then

  Fill0Char="0"&strVal

  Else

  Fill0Char=strVal

  EndIf

  EndFunction

  '------

  '设置上传文件大小上限(单位:Bytes),默认4096KB

  '------

  PublicPropertyLetMaxSize(lngVal)

  lngMaxSize=FormatNum(lngVal,4194304)

  EndProperty



  '------

  '返回上传状态代码

  '------

  PublicPropertyGetCode()

  Code=strCode

  EndProperty



  PrivatePropertyLetCode(strVal)

  strCode=strVal

  EndProperty



  PublicSubGetFileData()

  DimbinCrLf,binBoundary

  DimlngFirstBoundary,lngEndBoundary

  DimstrInfoHeader,strFieldName,strContentType,strItemValue

  DimobjFileStream

  DimintPos'临时位置

  strContentType=""

  IflngRequestBytes<1Then

  Code=504

  ExitSub

  EndIf

  IflngMaxSize<>0AndlngRequestBytes>lngMaxSizeThen

  Code=502

  ExitSub

  EndIf

  SetobjUpStream=Server.CreateObject("Adodb.Stream")

  objUpStream.Mode=3

  objUpStream.Type=1

  objUpStream.Open

  SetobjConvertStream=Server.CreateObject("adodb.stream")

  objConvertStream.Mode=3

  objConvertStream.Charset="utf-8"



  binCrLf=ChrB(13)&ChrB(10)'换行符

  lngFirstBoundary=ParseChunk(objUpStream,binCrLf,1)

  binBoundary=SubBinString(1,lngFirstBoundary-1)'取得边界串

  SetobjFileStream=NewFileInfo_Cls

  DoWhileStrComp(SubBinString(lngFirstBoundary,2),binCrLf)=0

  lngFirstBoundary=lngFirstBoundary+2

  RemBegin分解表单项目

  IfstrContentType=""Then

  DoWhileTrue

  lngEndBoundary=ParseChunk(objUpStream,binCrLf,lngFirstBoundary)

  strInfoHeader=SubString(lngFirstBoundary,lngEndBoundary-lngFirstBoundary)

  lngFirstBoundary=lngEndBoundary+2

  intPos=InStr(strInfoHeader,":")

  IfintPos=0ThenExitDo

  IfintPos>0Then

  IfStrComp(Left(strInfoHeader,intPos-1),"Content-Disposition",1)=0Then

  '取表单项名称

  strFieldName=ExtractValue(strInfoHeader,intPos+1,"name")

  '取文件路径,取文件名称

  FileName=ExtractFileName(ExtractValue(strInfoHeader,intPos+1,"filename"))



  IfNotCheckSuffix(FileName)ThenExitSub

  ElseIfStrComp(left(strInfoHeader,intPos-1),"Content-Type",1)=0Then

  '取文件类型

  strContentType=Trim(Mid(strInfoHeader,intPos+1))

  EndIf

  EndIf

  Loop

  EndIf

  RemEnd表单项目结束

  IfFileName<>""Then

  '掐头后移入流对象

  MoveStreamobjUpStream,objFileStream.Stream,lngFirstBoundary

  lngEndBoundary=ParseChunk(objFileStream.Stream,binBoundary&binCrLf,1)

  '流对象去尾

  MoveStreamobjFileStream.Stream,objUpStream,lngEndBoundary

  lngFirstBoundary=lngFirstBoundary+2+LenB(binBoundary)

  Else

  lngEndBoundary=ParseChunk(objUpStream,binBoundary,lngFirstBoundary)

  strItemValue=SubString(lngFirstBoundary,lngEndBoundary-2-lngFirstBoundary)



  '移动位置

  lngFirstBoundary=lngEndBoundary+LenB(binBoundary)

  EndIf

  Loop

  Code=200

  FileSize=objFileStream.FileSize

  SetobjFso=Server.CreateObject("Scripting.FileSystemObject")

  CallCheckFile

  SetobjFso=Nothing

  objFileStream.SaveAs(Server.MapPath(AutoFilePath))

  SetobjFileStream=Nothing

  EndSub



  PrivateSubCheckFile()

  IfobjFso.FileExists(Server.MapPath(AutoFilePath))Then

  FileName="[1]"&strFileName

  CallCheckFile

  EndIf

  EndSub



  PrivateFunctionExtractValue(strString,startPos,strName)

  DimstrVal

  DimstrCurPos,intCurPos

  Dimn1,n2

  strVal=strString

  strCurPos=strName&"="""

  intCurPos=InStr(startPos,strVal,strCurPos)

  IfintCurPos>0Then

  n1=intCurPos+Len(strCurPos)

  n2=InStr(n1,strVal,"""")

  ifn2>n1thenExtractValue=Mid(strVal,n1,n2-n1)

  EndIf

  EndFunction



  PrivateFunctionSubBinString(StartPos,ReadLen)

  DimlngStartPos,lngReadLen

  DimbinBoundary

  lngReadLen=ReadLen

  IflngReadLen=0ThenSubBinString="":ExitFunction

  lngStartPos=StartPos

  IfobjUpStream.Size<lngStartPos+lngReadLen-1ThenReadChunk2StreamobjUpStream

  objUpStream.Position=lngStartPos-1

  binBoundary=objUpStream.Read(lngReadLen)

  SubBinString=MidB(binBoundary,1)

  EndFunction



  PrivateFunctionSubString(StartPos,ReadLen)

  DimlngStartPos,lngReadLen

  DimbinBoundary

  lngReadLen=ReadLen

  IflngReadLen=0ThenSubString="":ExitFunction

  lngStartPos=StartPos

  IfobjUpStream.Size<(lngStartPos+lngReadLen-1)ThenReadChunk2StreamobjUpStream

  objUpStream.Position=lngStartPos-1

  binBoundary=objUpStream.Read(lngReadLen)

  WithobjConvertStream

  .Type=1

  .Open

  .WritebinBoundary

  .Position=0

  .Type=2

  SubString=.ReadText

  .Close

  EndWith

  EndFunction



  Rem解析一个块

  PrivateFunctionParseChunk(obj,Boundary,StartPos)

  '读取块的起始位置,找到边界的位置(0表示没有)

  DimlngStartPos,lngFoundPos,lngBoundaryLen

  DimbinChunk

  lngStartPos=StartPos

  lngFoundPos=0

  lngBoundaryLen=LenB(Boundary)

  DoWhilelngFoundPos=0

  '数据流长度不够时,读取一个块(lngReadChunkBytes)

  Ifobj.Size<(lngStartPos+lngBoundaryLen-1)ThenReadChunk2Streamobj

  obj.Position=lngStartPos-1

  binChunk=obj.Read

  lngFoundPos=InstrB(binChunk,Boundary)

  '未找到边界,则向后移动一个位置

  IflngFoundPos=0ThenlngStartPos=lngStartPos+LenB(binChunk)-lngBoundaryLen+1

  Loop

  ParseChunk=lngStartpos+lngFoundPos-1

  EndFunction



  PrivateSubReadChunk2Stream(obj)

  IfResponse.IsClientConnected=FalsethenCode=501:ExitSub

  obj.Position=obj.Size

  obj.WriteRequest.BinaryRead(lngReadChunkBytes)

  EndSub



  PrivateSubMoveStream(FromStream,ToStream,StartPos)

  FromStream.Position=StartPos-1

  ToStream.Position=ToStream.Size

  FromStream.CopyToToStream

  FromStream.Position=StartPos-1

  '将流对象的结束设定到当前位置

  FromStream.SetEOS

  EndSub



  PrivateFunctionExtractFileName(strString)

  DimstrVal

  strVal=Replace(strString,Chr(0),"")

  strVal=Replace(strVal,"","")

  strVal=Replace(strVal,"..","")

  strVal=Replace(strVal,"'","")

  strVal=Replace(strVal,"[","")

  strVal=Replace(strVal,"]","")

  strVal=Replace(strVal,"<","")

  strVal=Replace(strVal,">","")

  strVal=Replace(strVal,"*","")

  strVal=Replace(strVal,"&","")

  ExtractFileName=Mid(strVal,InStrRev(strVal,"")+1)

  EndFunction



  PrivateFunctionCheckSuffix(strA)

  DimstrSeparate,strTempFileSuffix

  CheckSuffix=True

  strSeparate=",asp,asa,cer,aspx,php,cdx,htr,shtm,shtml,stm,idc,"

  FileSuffix=LCase(Mid(strA,InStrRev(strA,".")+1))



  strTempFileSuffix=","&strFileSuffix&","

  IfInStr(strSeparate,strTempFileSuffix)>0Then

  Code=505

  CheckSuffix=False

  ExitFunction

  EndIf

  EndFunction



  PrivateFunctionCreateFolder(strFolderPath)

  DimsPath,i,strTempPath,n,objFso,RootPath

  CreateFolder=False

  SetobjFso=Server.CreateObject("Scripting.FileSystemobject")

  IfobjFso.FolderExists(strFolderPath)Then

  CreateFolder=True

  ExitFunction

  EndIf

  RootPath=Server.MapPath("/")&""

  sPath=Split(strFolderPath,"")

  strTempPath=""

  n=UBound(Split(RootPath,""))

  Fori=nToUBound(sPath)

  strTempPath=strTempPath&sPath(i)&""

  IfNotobjFso.FolderExists(RootPath&strTempPath)Then

  objFso.CreateFolder(RootPath&strTempPath)

  EndIf

  Next

  SetobjFso=Nothing

  IfErr=0Then

  CreateFolder=True

  Else

  CreateFolder=False

  EndIf

  EndFunction



  PrivateFunctionFormatNum(intVal,DefaultVal)

  IfNotIsNumeric(intVal)Then

  FormatNum=Clng(DefaultVal)

  Else

  FormatNum=Clng(intVal)

  EndIf

  EndFunction



  EndClass



  ClassFileInfo_Cls

  PrivateobjFileStream



  PublicFunctionFileSize()

  DimlngSize

  lngSize=objFileStream.Size

  FileSize=CLng(lngSize/1024)

  EndFunction



  PublicPropertyGetStream()

  SetStream=objFileStream

  EndProperty



  PublicSubSaveAs(strFilePath)

  OnErrorResumeNext

  objFileStream.SaveToFilestrFilePath,2

  IfErr.Number>0ThenResponse.Write"UploadErr:"&Err.Description&"<br>":ExitSub

  EndSub



  PrivateSubClass_Initialize

  SetobjFileStream=CreateObject("Adodb.Stream")

  objFileStream.Mode=3

  objFileStream.Type=1

  objFileStream.Open

  Endsub



  PrivateSubClass_Terminate

  objFileStream.Close

  SetobjFileStream=Nothing

  Endsub



  EndClass



  Dimaction

  DimobjUpload,objFile



  action=Trim(Request.QueryString("action"))

  Response.Write"<br>"

  SelectCaseaction

  Case"save"

  CallSave

  Case"list"

  CallFileList

  CaseElse

  CallHeader

  EndSelect

  SubSave()

  Dimstime,etime

  stime=Timer

  SetobjUpload=NewUpload_Cls

  objUpload.AllowSuffix=""

  objUpload.MaxSize=0

  objUpload.SetFilePathUPLOAD_PATH,1

  CallobjUpload.GetFileData

  etime=Timer

  Response.Write"上传执行代码Code:"&objUpload.Code&"<br>"

  Response.Write"文件路径:"&objUpload.AutoFilePath&"<br>"

  Response.Write"文件大小:"&objUpload.FileSize&"KB<br>"

  Response.Write"执行时间:"&FormatNumber((etime-stime),2)&"second"

  SetobjUpload=Nothing

  CallHeader

  EndSub

  SubHeader()

  %>

  <html>

  <head>

  <metahttp-equiv="Content-Type"content="text/html;charset=utf-8">

  <title></title>

  <tablewidth="600"border="0"cellspacing="0"cellpadding="0">

  <br><br><br><br><br>

  'Code:200(上传成功)、504(文件为空)、502(上传上限)、501(表示网络中断)、500(上传错误)、

  '505(文件类型禁止上传),506(未设置允许的文件后缀),507(未设置上传路径)

  <formaction="?action=save"method="post"enctype="multipart/form-data"name="form1">

  <tralign="center">

  <tdwidth="80"height="46">选择地址:</td>

  <tdwidth="300">

  <inputname="uploadfile"type="file"id="uploadfile"size="30"></td>

  <tdwidth="60"><inputtype="submit"name="Submit"value="上传"></td>

  </tr>

  <tralign="center">

  <tdheight="20"colspan="3"><inputtype="button"name="Submit"value="关闭"onClick="window.close();"></td>

  </tr>

  </form>

  </table>

  <%

  EndSub



  SubFileList()

  DimstrPath

  DimobjFso,objUpload

  DimobjFolders,objFiles,Folder,File

  DimstrThisPath

  SetobjUpload=NewUpload_Cls

  strPath=Trim(Request.QueryString("path"))

  IfLen(strPath)=0Then

  strThisPath=UPLOAD_PATH&objUpload.FormatTimePattern(Now(),"ymd")&"/"

  ElseIfCStr(LCase(strPath))="/upload/"Then

  strThisPath=UPLOAD_PATH

  Else

  strThisPath=UPLOAD_PATH&strPath

  EndIf

  %>

  <html>

  <head>

  <metahttp-equiv="Content-Type"content="text/html;charset=utf-8">

  <title></title>

  <br>



  <tablewidth="780"align="center"border="0"cellspacing="1"cellpadding="0"bgcolor="#CCCCCC">

  <ahref="?action=list&path=/upload/">返回上一个路径:</a>

  <br><br>

  当前路径:<%Response.WritestrThisPath%>

  <br><br>

  <trbgcolor="#EFEFEF">

  <tdalign="center"class="row-pathtopic">文件夹/文件名</a></td>

  <tdalign="center"height="30">大小</td>

  <tdalign="center">文件类型</td>

  <tdalign="center">创建时间</td>

  <tdalign="center">修改时间</td>

  </tr>

  <%

  SetobjFso=Server.CreateObject("Scripting.FileSystemObject")

  SetobjFolders=objFso.GetFolder(Server.MapPath(strThisPath))

  ForEachFolderInobjFolders.subFolders

  %>

  <trbgcolor="#FFFFFF">

  <tdheight="30"><ahref="?action=list&path=<%=Folder.Name%>"><%=Folder.Name%></a></td>

  <tdalign="center"><%=FileSize(Folder.Size)%></td>

  <tdalign="center"><%=Folder.Type%></td>

  <tdalign="center"><atitle="创建时间"><%=objUpload.FormatTimePattern(Folder.DateCreated,"y-m-dh:n:s")%></a></td><td><atitle="修改时间"><%=objUpload.FormatTimePattern(Folder.DateLastModified,"y-m-dh:n:s")%></a></td>

  </tr>

  <%

  Next



  ForEachFileInobjFolders.Files

  %>

  <trbgcolor="#FFFFFF">

  <tdheight="30"><ahref="<%=strThisPath&"/"&File.Name%>"><%=File.Name%></a></td>

  <tdalign="center"><%=FileSize(File.Size)%></td>

  <tdalign="center"><%=File.Type%></td>

  <tdalign="center"><atitle="创建时间"><%=objUpload.FormatTimePattern(File.DateCreated,"y-m-dh:n:s")%></a></td><td><atitle="修改时间"><%=objUpload.FormatTimePattern(File.DateLastModified,"y-m-dh:n:s")%></a></td>

  </tr>

  <%

  Next

  SetobjFolders=Nothing

  SetobjFso=Nothing

  SetobjUpload=Nothing

  %>

  </table>

  </body>

  </html>

  <%

  EndSub



  FunctionFileSize(intSize)

  FileSize=CLng(intSize/1024)&"K"

  EndFunction

  %>
本文标题:asp文件上传-[ASP.NET] 限制上传文件类型的两种方法
本文地址: http://www.61k.com/1060443.html

61阅读| 精彩专题| 最新文章| 热门文章| 苏ICP备13036349号-1