ASP的文件上传示例

这个有好几个文件:
test.html为调用页面,其它几个为上传功能页面,把这四个文件放在同一目录下,然后建立站点运行test.html页面,点击 上传图片 即可看到效果。

test.html代码如下:

<!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>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title></title>
<script LANGUAGE="javascript"> 
<!-- 
function openwin(name) {
var n=name;
window.open ("upload.asp?n="+n, "图片上传", "height=50, width=500, toolbar =no, menubar=no, scrollbars=yes, resizable=no, location=no, status=no")

//--> 
</script>
<style type="text/css">
<!--
td {height:20px;}
-->
</style>
</head>

<body>
<table width="95%" border="0" align="center" style="margin-bottom:15px; margin-top:15px;">
 <tr class="td_bg1">
   <td><div align="right">图片地址</div></td>
   <td><div align="left"><input name="b20" type="text" id="b20" value="" size="40">
    <a href="#" οnclick="openwin('b20')">上传图片</a></div></td>
 </tr>
</table>
</body>
</html>

upload.asp代码如下:

<%On error resume next
n=request("n")
if n="" then
response.end()
end if%>
<style type="text/css">
<!--
body {
 margin-left: 2px;
 margin-top: 0px;
 background-color: #9dacbf;
}
.STYLE1 {font-size:12px; color:#0000ff;}
-->
</style>
<meta http-equiv="content-type" content="text/html;charset=gb2312">
<form name="formb" method="post" action="upfile.asp?n=<%=n%>" enctype="multipart/form-data">
<input type="hidden" name="upfilefolder" value="uploadfile">
<input type="hidden" name="act" value="upload">
<input type="file" name="file11" size=40>
<input type="submit" name="Submit" value=" 上传 " onclock="javascript:document.formb.Submit.disabled=false"><span class="STYLE1">(图片大小&lt;=2M)</span>
</form>

upfile.asp代码如下:

<%@LANGUAGE="VBSCRIPT" CODEPAGE="936"%>
<%Server.ScriptTimeOut=180
On error resume next%>
<%n=request("n")
if n="" then
response.end
end if%> 
<!--#include file="upload.inc"-->
<html>
<head>
<title>文件上传</title>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<style type="text/css">
<!--
body {background-color: #9dacbf;margin-left: 2px; margin-top:0px;}
-->
</style></head>
<body>
<%
Function RegExpTest(patrn,str,alert)
Set regEx = New RegExp
regEx.Pattern = patrn
regEx.IgnoreCase = True
if not(regEx.Test(str)) then
response.write "<font size='2' color='0000ff'>文件路径名出错 [ <a href=# οnclick=window.close();>关闭窗口</a> ]</font>"
response.end
end if
End Function
dim upload,f_folder,file,formPath,iCount,filename,fileExt,filesizemin,filesizemax

filesizemin=100
filesizemax=4096*1024
set upload=new upload_5xSoft '建立上传对象
f_folder=trim(upload.form("upfilefolder"))
Call RegExpTest("^[a-zA-Z0-9]{1,20}$",f_folder,"")

'********************************列出所有上传文件***************************************************
For each formName in upload.objFile
set file=upload.file(formName)
If file.filesize>0 then

    '********************************检测文件大小***************************************************
    If file.filesize<filesizemin Then
        response.write "<font size='2' color='0000ff'>你上传的文件太小了 [ <a href=# οnclick=history.go(-1)>重新上传</a> ]</font>"
        response.end
    ElseIf file.filesize>filesizemax then
        response.write "<font size='2' color='0000ff'>文件大小超过了 "&(filesizemax/(1024*1024))&" M 限制 [ <a href=# οnclick=history.go(-1)>重新上传</a> ]</font>"
        response.end
    End If

    '********************************检测文件类型****************************************************
    fileExt=ucase(right(file.filename,4))
    uploadsuc=false
 '允许的文件类型
    Forum_upload="RAR|ZIP|SWF|JPG|PNG|GIF|DOC|TXT|CHM|PDF|ACE|MP3|WMA|WMV|MIDI|AVI|RM|RA|RMVB|MOV|XLS"
    Forumupload=split(Forum_upload,"|")
    for i=0 to ubound(Forumupload)
        if fileEXT="."&trim(Forumupload(i)) then
            uploadsuc=true
            exit for
        else
            uploadsuc=false
        end if
    next
    if uploadsuc=false then
        response.write "<font size='2' color='0000ff'>文件格式不正确 [ <a href=# οnclick=history.go(-1)>重新上传</a> ]</font>"
        response.end
    end if

    '********************************建立文件上传的目录文件夹****************************************
    Set upf=Server.CreateObject("Scripting.FileSystemObject")
    If Err<>0 Then
        Err.Clear
        response.write("<font size='2' color='0000ff'>您的服务器不支持FSO</font>")
        response.end
    End If
    f_type= replace(fileExt,".","")
    f_name= year(now)&"-"&month(now)
    If upf.FolderExists(Server.MapPath(f_folder&"/"&f_type&"/"&f_name))=False Then
        If upf.FolderExists(Server.MapPath(f_folder&"/"&f_type))=False Then
            If upf.FolderExists(Server.MapPath(f_folder))=False Then
                upf.CreateFolder Server.MapPath(f_folder)
                upf.CreateFolder Server.MapPath(f_folder&"/"&f_type)
                upf.CreateFolder Server.MapPath(f_folder&"/"&f_type&"/"&f_name)
            Else
                upf.CreateFolder Server.MapPath(f_folder&"/"&f_type)
                upf.CreateFolder Server.MapPath(f_folder&"/"&f_type&"/"&f_name)
            End If
        Else
            upf.CreateFolder Server.MapPath(f_folder&"/"&f_type&"/"&f_name)
        End If
    End If
    f_ftn=f_folder&"/"&f_type&"/"&f_name
    Set upf=Nothing

    '********************************保存上传文件至文件夹*****************************************
    randomize
    ranNum=int(90000*rnd)+10000
 ranNum2=int(90000*rnd)+10000
    filename=f_ftn&"/"&year(now())&month(now())&day(now())&hour(now())&minute(now())&second(now())&"-"&ranNum&"-"&ranNum2&fileExt
    if file.filesize>filesizemin and file.filesize<filesizemax then
    file.SaveAs Server.mappath(filename)  '保存文件
        iCount=iCount+1
    end if
set file=nothing
end if
next
set upload=nothing '删除此对象

filename="upload/"&filename
response.write("<script>opener.document.getElementById("""&n&""").value="""&filename&""";window.close();</script>")
filename=""
%>
</body>
</html>

upload.inc代码如下:

<SCRIPT RUNAT=SERVER LANGUAGE=VBSCRIPT>
dim Data_5xsoft

Class upload_5xsoft
 
dim objForm,objFile,Version

Public function Form(strForm)
  strForm=lcase(strForm)
  if not objForm.exists(strForm) then
   Form=""
  else
   Form=objForm(strForm)
  end if
 end function

Public function File(strFile)
  strFile=lcase(strFile)
  if not objFile.exists(strFile) then
   set File=new FileInfo
  else
   set File=objFile(strFile)
  end if
 end function


Private Sub Class_Initialize 
 dim RequestData,sStart,vbCrlf,sInfo,iInfoStart,iInfoEnd,tStream,iStart,theFile
 dim iFileSize,sFilePath,sFileType,sFormValue,sFileName
 dim iFindStart,iFindEnd
 dim iFormStart,iFormEnd,sFormName
 Version="化境HTTP上传程序 Version 2.0"
 set objForm=Server.CreateObject("Scripting.Dictionary")
 set objFile=Server.CreateObject("Scripting.Dictionary")
 if Request.TotalBytes<1 then Exit Sub
 set tStream = Server.CreateObject("adodb.stream")
 set Data_5xsoft = Server.CreateObject("adodb.stream")
 Data_5xsoft.Type = 1
 Data_5xsoft.Mode =3
 Data_5xsoft.Open
 Data_5xsoft.Write Request.BinaryRead(Request.TotalBytes)
 Data_5xsoft.Position=0
 RequestData =Data_5xsoft.Read

 iFormStart = 1
 iFormEnd = LenB(RequestData)
 vbCrlf = chrB(13) & chrB(10)
 sStart = MidB(RequestData,1, InStrB(iFormStart,RequestData,vbCrlf)-1)
 iStart = LenB (sStart)
 iFormStart=iFormStart+iStart+1
 while (iFormStart + 10) < iFormEnd 
    iInfoEnd = InStrB(iFormStart,RequestData,vbCrlf & vbCrlf)+3
    tStream.Type = 1
    tStream.Mode =3
    tStream.Open
    Data_5xsoft.Position = iFormStart
    Data_5xsoft.CopyTo tStream,iInfoEnd-iFormStart
    tStream.Position = 0
    tStream.Type = 2
    tStream.Charset ="gb2312"
    sInfo = tStream.ReadText
    tStream.Close
    '取得表单项目名称
    iFormStart = InStrB(iInfoEnd,RequestData,sStart)
    iFindStart = InStr(22,sInfo,"name=""",1)+6
    iFindEnd = InStr(iFindStart,sInfo,"""",1)
    sFormName = lcase(Mid (sinfo,iFindStart,iFindEnd-iFindStart))
    '如果是文件
    if InStr (45,sInfo,"filename=""",1) > 0 then
        set theFile=new FileInfo
        '取得文件名
        iFindStart = InStr(iFindEnd,sInfo,"filename=""",1)+10
        iFindEnd = InStr(iFindStart,sInfo,"""",1)
        sFileName = Mid (sinfo,iFindStart,iFindEnd-iFindStart)
        theFile.FileName=getFileName(sFileName)
        theFile.FilePath=getFilePath(sFileName)
        '取得文件类型
        iFindStart = InStr(iFindEnd,sInfo,"Content-Type: ",1)+14
        iFindEnd = InStr(iFindStart,sInfo,vbCr)
        theFile.FileType =Mid (sinfo,iFindStart,iFindEnd-iFindStart)
        theFile.FileStart =iInfoEnd
        theFile.FileSize = iFormStart -iInfoEnd -3
        theFile.FormName=sFormName
        if not objFile.Exists(sFormName) then
         objFile.add sFormName,theFile
        end if
    else
    '如果是表单项目
        tStream.Type =1
        tStream.Mode =3
        tStream.Open
        Data_5xsoft.Position = iInfoEnd 
        Data_5xsoft.CopyTo tStream,iFormStart-iInfoEnd-3
        tStream.Position = 0
        tStream.Type = 2
        tStream.Charset ="gb2312"
        sFormValue = tStream.ReadText 
        tStream.Close
        if objForm.Exists(sFormName) then
         objForm(sFormName)=objForm(sFormName)&", "&sFormValue         
        else
         objForm.Add sFormName,sFormValue
        end if
    end if
    iFormStart=iFormStart+iStart+1
    wend
 RequestData=""
 set tStream =nothing
End Sub

Private Sub Class_Terminate 
 if Request.TotalBytes>0 then
    objForm.RemoveAll
    objFile.RemoveAll
    set objForm=nothing
    set objFile=nothing
    Data_5xsoft.Close
    set Data_5xsoft =nothing
 end if
End Sub
  
 
 Private function GetFilePath(FullPath)
 If FullPath <> "" Then
  GetFilePath = left(FullPath,InStrRev(FullPath, "\"))
 Else
  GetFilePath = ""
 End If
 End function
 
 Private function GetFileName(FullPath)
 If FullPath <> "" Then
  GetFileName = mid(FullPath,InStrRev(FullPath, "\")+1)
 Else
  GetFileName = ""
 End If
 End function
End Class

Class FileInfo
 dim FormName,FileName,FilePath,FileSize,FileType,FileStart
 Private Sub Class_Initialize 
  FileName = ""
  FilePath = ""
  FileSize = 0
  FileStart= 0
  FormName = ""
  FileType = ""
 End Sub
 
 Public function SaveAs(FullPath)
  dim dr,ErrorChar,i
  SaveAs=true
  if trim(fullpath)="" or FileStart=0 or FileName="" or right(fullpath,1)="/" then exit function
  set dr=CreateObject("Adodb.Stream")
  dr.Mode=3
  dr.Type=1
  dr.Open
  Data_5xsoft.position=FileStart
  Data_5xsoft.copyto dr,FileSize
  dr.SaveToFile FullPath,2
  dr.Close
  set dr=nothing 
  SaveAs=false
 end function
 End Class
</SCRIPT>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
下面是一个使用ASP.NET的文件上传的代码示例: ```csharp <%@ Page Language="C#" %> <!DOCTYPE html> <html> <head> <title>文件上传示例</title> </head> <body> <form id="form1" runat="server" enctype="multipart/form-data"> <input type="file" id="fileUpload" runat="server" /> <br /> <asp:Button ID="btnUpload" runat="server" Text="上传" OnClick="btnUpload_Click" /> </form> </body> </html> ``` 在后端代码中,你可以处理文件上传的逻辑。在这个示例中,我们将上传的文件保存到服务器上的一个特定目录中: ```csharp using System; using System.IO; public partial class FileUploadExample : System.Web.UI.Page { protected void btnUpload_Click(object sender, EventArgs e) { if (fileUpload.HasFile) { try { string filename = Path.GetFileName(fileUpload.FileName); string saveLocation = Server.MapPath("~/uploads/") + filename; fileUpload.SaveAs(saveLocation); // 可以在这里执行其他操作,如将文件信息保存到数据库中 Response.Write("文件上传成功!"); } catch (Exception ex) { Response.Write("文件上传发生错误: " + ex.Message); } } else { Response.Write("请选择要上传的文件!"); } } } ``` 在这个示例中,我们首先检查是否选择了要上传的文件。然后,我们获取文件名和保存路径,并使用SaveAs方法将文件保存到服务器上的指定位置。你可以根据需要进行进一步的处理,比如将文件信息保存到数据库中。最后,我们在页面上显示上传成功或错误的消息。 请注意,为了使文件上传正常工作,你需要确保服务器上存在用于保存上传文件的目录,并且该目录对应用程序具有写入权限。在这个示例中,我们假设存在一个名为"uploads"的目录用于保存上传的文件。 希望这个示例对你有帮助!

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值