ASP no component File upload instance

Source: Internet
Author: User
Tags comments extend file upload save file servervariables trim

<!--#include file= "pf_upload_class.asp"-->


<!doctype HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "http://www.w3.org/tr/xhtml1/dtd/ Xhtml1-transitional.dtd ">


<html xmlns= "http://www.111cn.net/1999/xhtml" >


<head>


<meta http-equiv= "Content-type" content= "text/html; charset=gb2312 "/>


<title> File Upload </title>


<style>


* {


margin:0;


padding:0;


}


Body {


Font-family: "The song Body";


font-size:12px;


Background: #f1f1f1;


}


Input, select, textarea {


border:1px solid #ccc;


font-size:12px;


padding:2px;


}


</style>


</head>


<body>


<%


If Request.QueryString ("act") = "Upload" Then


Dim upload,path,tempcls,fname


'===============================================================================


Set Upload=new anupload ' Create class instance


upload.singlesize=1024*1024*1024 ' Set maximum upload limit for single file, by byte; default is Unrestricted


upload.maxsize=1024*1024*1024 ' Set maximum upload limit, by byte; default is Unrestricted


Upload.exe= "Jpg|jpeg|gif|png|zip|rar|7z|pdf|doc" ' Set legal extension to | split, ignoring case


upload.charset= "gb2312" sets the text encoding by default to GB2312


Upload.openprocesser=false ' Prohibit progress bar function, if enabled, need to cooperate with client program


Upload.getdata () ' Gets and saves data, must call this method


'===============================================================================


If Upload.errorid>0 then ' Judge error number, if myupload.err<=0 indicates normal


Response.Write Upload.description ' If an error occurs, get the description of the error


Else


If Upload.files ( -1). Count>0 then ' here to determine if you have selected the file


Path=server.mappath (".. /uploadfile ")" File Save path (here is the Files folder)


' Save file (saved with new file name)


Set Tempcls=upload.files ("File1")


Tempcls.savetofile path,0


Fname=tempcls.filename


Set tempcls=nothing


Else


Response.Write "You didn't upload any files!" "


End If


End If


Set Upload=nothing ' Destroy class instance


%>


<script type = "text/web Effects" >


Window.parent.document.pcfinal.pf_uploadfile.value= ' uploadfile/<%=fname%> ';


</script>


<%


Else


%>


<form name= "Upload" method= "post" action= "Pf_upload.asp?act=upload" enctype= "Multipart/form-data" >


<input type = "File" name = "File1"/>


<input type = "Submit" value= "Upload" style= "height:20px"/>


</form>


<%


End If


%>


</body>


</html>

Save the following code as pf_upload_class.asp

<%

Class Anupload
Private form, fils
Private Vcharset, Vmaxsize, Vsinglesize, Verr, Vversion, Vtotalsize, Vexe, PID, VOP, Verrexe, Vboundary, Vlosttime, Vmode, Vfilecount

'==============================
' Set and Read properties start
'==============================

Public Property Let Mode (ByVal value)
Vmode = value
End Property

Public Property Let MaxSize (ByVal value)
Vmaxsize = value
End Property

Public Property Let Singlesize (ByVal value)
Vsinglesize = value
End Property

Public Property Let EXE (ByVal value)
Vexe = LCase (value)
End Property

Public Property Let CharSet (ByVal value)
Vcharset = value
End Property

Public Property Get ErrorID ()
ErrorID = Verr
End Property

Public Property Get FileCount ()
FileCount = Fils.count
End Property

Public Property Get Description ()
Description = Geterr (Verr)
End Property

Public Property Get Version ()
Version = Vversion
End Property

Public Property Get TotalSize ()
TotalSize = Vtotalsize
End Property

Public Property Get ProcessID ()
ProcessID = pid
End Property

Public Property Let Openprocesser (ByVal value)
VOP = value
End Property

Public Property Get Losttime ()
Losttime = Vlosttime
End Property

'==============================
' Set and read property end, initialize class
'==============================

    Private Sub Class_Initialize ()
        Set form = Server.CreateObject ("Scripting.Dictionary")
        Set fils = Server.CreateObject ("Scripting.Dictionary")
        vversion = " Al-Ain ASP No Component upload Class optimization (v9.11.1) "
        vmaxsize =-1
         vsinglesize =-1
        verr =-1
         Vexe = ""
        vtotalsize = 0
         vcharset = "gb2312"
        VoP = False
        pid = "Anupload"
        Setapp "" , 0, 0, ""
        vmode = 0
    End Sub

Private Sub Class_Terminate ()
Dim f
Form.removeall ()
For each F in fils
Fils (f). Value = Empty
Set fils (f) = Nothing
Next
Fils.removeall ()
Set form = Nothing
Set fils = Nothing
End Sub

'==============================
' Function name: GetData
' Function: Handle all data submitted by client
'==============================

Public Sub GetData ()


Dim time1


time1 = Timer ()


If VOP then pid = Request.QueryString ("ProcessID")


Dim value, str, BCRLF, FPOs, Ssplit, Slen, Istart, EF


Dim totalbytes, TempData, Bytesread, Chunkreadsize, Partsize, Datapart, Formend, Formhead, Startpos, Endpos, FormName, fil ename, Fileexe, ValueEnd, NewName, LocalName, Type_1, contenttype


TotalBytes = Request.TotalBytes


EF = False


If Checkentrytype = False Then


EF = True


Verr = 2


End If


' The following 3 comments were dropped because in iis5.0, if the upload size is greater than the size of the file, there will be errors and no solution has been found. If you are using the version above IIS5, you can cancel the comments in the following 3 sentences


' If not EF then


' If vmaxsize &gt; 0 and totalbytes &gt; vmaxsize then ef = True:verr = 1


' End If


If EF then Exit Sub


If Vmode = 0 Then


Vtotalsize = 0


Dim Streamt


Set Streamt = Server.CreateObject ("ADODB.stream")


Streamt.type = 1


Streamt.mode = 3


Streamt.open


Bytesread = 0


Chunkreadsize = 1024 * 16


Do While Bytesread &lt; totalbytes


Partsize = Chunkreadsize


If Partsize + bytesread &gt; totalbytes then partsize = Totalbytes-bytesread


Datapart = Request.BinaryRead (partsize)


Streamt.write Datapart


Bytesread = Bytesread + partsize


Setapp "Uploading", TotalBytes, Bytesread, ""


Loop


Setapp "uploaded", totalbytes, Bytesread, ""


streamt.position = 0


TempData = Streamt.read


Streamt.close ()


Set Streamt = Nothing


Else


TempData = Request.BinaryRead (totalbytes)


End If


Bcrlf = ChrB (+) &amp; ChrB (10)


FPOs = INSTRB (1, TempData, BCRLF)


Ssplit = MidB (TempData, 1, fpos-1)


Slen = LenB (ssplit)


Istart = Slen + 2


Do While LenB (TempData) &gt; 2 + slen


Formend = INSTRB (Istart, TempData, Bcrlf &amp; Bcrlf)


Formhead = MidB (TempData, Istart, Formend-istart)


str = BYTES2STR (formhead)


startpos = InStr (str, "name=" "") + 6


Endpos = InStr (Startpos, str, "" ")


FormName = LCase (Mid (str, startpos, Endpos-startpos))


ValueEnd = INSTRB (Formend + 3, TempData, Ssplit)


If InStr (str, "filename=" "") &gt; 0 Then


startpos = InStr (str, "filename=" "") + 10


Endpos = InStr (Startpos, str, "" ")


Type_1 = InStr (Endpos, LCase (str), "Content-type")


ContentType = Trim (Mid (str, type_1 + 13))


filename = Mid (str, startpos, Endpos-startpos)


If trim (filename) &lt;&gt; "" Then


LocalName = filename


filename = replace (filename, "/", "")


filename = Mid (filename, InStrRev (filename, "") + 1)


If InStr (FileName, ".") &gt;0 Then


Fileexe = split (filename, ".") (UBound (FileName, "."))


Else


Fileexe = ""


End If


If Vexe &lt;&gt; "then" Judge extension


If Checkexe (fileexe) = True Then


Verr = 3


Verrexe = Fileexe


TempData = Empty


Exit Sub


End If


End If


newname = GetName ()


newname = newname &amp; "." &amp; Fileexe


Vtotalsize = vtotalsize + valueend-formend-6


If Vsinglesize &gt; 0 and (valueend-formend-6) &gt; Vsinglesize Then ' Judge upload single file size


Verr = 5


TempData = Empty


Exit Sub


End If


If vmaxsize &gt; 0 and vtotalsize &gt; vmaxsize Then ' Judge the total size of uploaded data


Verr = 1


TempData = Empty


Exit Sub


End If


If Fils.exists (FormName) Then


Verr = 4


TempData = Empty


Exit Sub


Else


Dim filecls


Set filecls = Getnewfileobj ()


Filecls.contenttype = ContentType


Filecls.size = (valueend-formend-5)


Filecls.formname = FormName


Filecls.newname = newname


Filecls.filename = filename


Filecls.localname = filename


Filecls.extend = Split (NewName, ".") (UBound (Split (NewName, "."))


Filecls.value = MidB (tempdata, Formend + 4, valueend-formend-5)


Fils.add FormName, Filecls


Set filecls = Nothing


End If


End If


Else


Value = MidB (tempdata, Formend + 4, valueend-formend-6)


If Form.exists (FormName) Then


Form (formname) = form (FormName) &amp; "," &amp; Bytes2str (value)


Else


Form.add FormName, Bytes2str (value)


End If


End If


Istart = 2 + slen


TempData = MidB (TempData, ValueEnd + 2)


Loop


Verr = 0


TempData = Empty


Vlosttime = FormatNumber ((timer-time1) * 1000, 2)


End Sub

Public Sub Setapp (STP, total, current, desc)
Application.Lock ()
Application (PID) = "{id:" "" & pid & "" ", Step:" "& STP &" ", Total:" & Total & ", now:" & Curre NT & ", Description:" "& Desc &" ", dt:" "& Now () &" "}"
Application.UnLock ()
End Sub

'==============================
' Judge the extension
'==============================

Private Function Checkexe (ByVal Ex)


Dim notin


Notin = True


If Vexe = "*" Then


Notin = False


ElseIf InStr (1, Vexe, "|") &gt; 0 Then


Dim Tempexe


Tempexe = Split (Vexe, "|")


Dim i


i = 0


For i = 0 To UBound (tempexe)


If LCase (ex) = Tempexe (i) Then


Notin = False


Exit For


End If


Next


Else


If Vexe = LCase (ex) Then


Notin = False


End If


End If


Checkexe = Notin


End Function

'==============================
' Convert numbers to file size display
'==============================

Public Function GetSize (ByVal size)
If size < 1024 Then
GetSize = FormatNumber (size, 2) & "B"
ElseIf size >= 1024 and size < 1048576 Then
GetSize = FormatNumber (size/1024, 2) & "KB"
ElseIf size >= 1048576 Then
GetSize = FormatNumber ((size/1024)/1024, 2) & "MB"
End If
End Function

'==============================
' binary data converted to characters
'==============================

Private Function Bytes2str (ByVal byt)


If LenB (byt) = 0 Then


Bytes2str = ""


Exit function


End If


Dim MyStream, BSTR


Set mystream = Server.CreateObject ("ADODB.stream")


Mystream.type = 2


Mystream.mode = 3


Mystream.open


Mystream.writetext byt


mystream.position = 0


Mystream.charset = Vcharset


Mystream.position = 2


BSTR = Mystream.readtext ()


Mystream.close


Set MyStream = Nothing


Bytes2str = BSTR


End Function

'==============================
' Get the description of the error
'==============================

Private Function Geterr (ByVal num)


Select Case num


Case 0


Geterr = "Data processing completed!"


Case 1


Geterr = "Upload data exceeds &amp; GetSize (vmaxsize) &amp;" Limit! You can set the MaxSize property to change the limit! "


Case 2


Geterr = "The upload form is not set Enctype property is Multipart/form-data or the method property is not set to post, upload is invalid!"


Case 3


Geterr = "contains illegal extension (" &amp; Verrexe &amp; ") file! can only upload files with extension" &amp; Replace (Vexe, "|", ",") &amp; "


Case 4


Geterr = "Sorry, the program does not allow file domains with the same name property!"


Case 5


Geterr = "Single file size exceeds the upload limit of &amp; GetSize (vsinglesize) &amp;"!


End Select


End Function

'==============================
' Generate random file names based on date
'==============================

Private Function GetName ()


Dim y, M, D, H, MM, S, r


Randomize


y = year (now)


m = Month (now)


If M &lt; then M = "0" &amp; M


D = Day (now)


If d &lt; then d = "0" &amp; D


H = Hour (now)


If H &lt; ten then H = "0" &amp; H


MM = Minute (now)


If mm &lt; then mm = "0" &amp; mm


s = Second (now)


If s &lt; then S = "0" &amp; S


R = 0


R = CInt (Rnd () * 1000)


If r &lt; r = "then" &amp; R


If R &lt; R &gt;= then r = "0" &amp; R


GetName = y &amp; M &amp; D &amp; H &amp; mm &amp; S &amp; R


End Function

'==============================
' Detect if the upload type is Multipart/form-data
'==============================

Private Function Checkentrytype ()


Dim contenttype, Ctarray, Barray, Requestmethod


Requestmethod = Trim (LCase (Request.ServerVariables ("Request_method"))


If Requestmethod = "" or requestmethod&lt;&gt; "post" then


Checkentrytype = False


Exit function


End If


ContentType = LCase (Request.ServerVariables ("Http_content_type"))


Ctarray = Split (contenttype, ";")


If UBound (Ctarray) &gt;= 0 Then


If Trim (Ctarray (0)) = "Multipart/form-data" Then


Checkentrytype = True


Vboundary = Split (contenttype, "boundary=") (1)


Else


Checkentrytype = False


End If


Else


Checkentrytype = False


End If


End Function

'==============================
' Get upload form value, parameter optional, IF-1 returns a Dictionary object containing all the table items
'==============================

    Public Function Forms (ByVal formname)
        if Trim ( FormName) = "-1" then
            set forms = Form
        Else
             If Form.exists (LCase (formname)) then
                 forms = Form (LCase (formname))
             Else
                Forms = ""
            End If
         End If
    End Function

    ' ==============================
    ' get uploaded file classes, parameters optional, If-1 Returns a Dictionary object containing all uploaded file classes
    ' ==============================

    Public Function Files (ByVal formname)
        if Trim ( FormName) = "-1" then
            set files = Fils
        Else
             If Fils.exists (LCase (formname)) then
                 Set files = Fils (LCase (formname))
             Else
                 Set files = Nothing
            End If
         End If
    End Function

End Class
%>
<script language= "JScript" runat= "Server" >
function Getnewfileobj () {
return new UploadFile ();
}
function UploadFile () {
This.formname= "";
This.newname = "";
This.localname= "";
This.filename= "";
This.usersetname= "";
This.contenttype= "";
this.size=0;
This.value=null;
This.path = "";
This.extend= "";
}

How to save a file


Uploadfile.prototype.savetofile=function () {


var arg = arguments;


var path, option, overwrite


if (arg.length==0) {return {error:true,description: ' parameter error, pass at least one parameter '};}


if (arg.length==1) {path = Arg[0];option=0;overwrite=true;}


if (arg.length==2) {path = Arg[0];option=arg[1];overwrite=true;}


if (arg.length==3) {path = arg[0];option=arg[1];overwrite=arg[2];}


if (arg.length&gt;3) {return {error:true,description: ' parameter error, pass up to 3 arguments '};}


try{


var ISP = (Path.indexof (":") ==1)


if (!isp) {


Path = Server.MapPath (path);


}


Path = Path.replace ("/", "");


if (Path.substr (path.length-1,1)!= "") {Path = path + "";}


This.createfolder (path);


This.path = path;


if (option==1) {


Path = path + This.localname;this.filename = This.localname;


}else{


if (option==-1 &amp;&amp; this.usersetname!= "") {


Path = path + This.usersetname + "." + This.extend;this.filename = This.usersetname + "." + this.extend;


}else{


Path = path + This.newname;this.filename = This.newname;


}


}


if (!overwrite) {


Path = This.getfilepath ();


}


var tmps tutorial TRM;


TMPSTRM = Server.CreateObject ("ADODB.stream");


tmpstrm.mode=3;


Tmpstrm.type= 1;


Tmpstrm.open ();


var info = Server.CreateObject ("Adodb.recordset");


Info.fields.append ("value", 205,-1);


Info.open ();


Info.addnew ();


Info ("value"). AppendChunk (This.value);


Tmpstrm.write (Info ("value"));


Info ("value"). AppendChunk (NULL);


Info.update ();


Info.close ();


info = null;


Tmpstrm.savetofile (path,2);


Tmpstrm.close ();


TMPSTRM = null;


return {error:false,description: ' successfully save file '};


}catch (ex) {


return {error:true,description:ex.description};


}


};


Ways to get Binary data


Uploadfile.prototype.getbytes=function () {


Return This.value


};

Uploadfile.prototype.createfolder=function (FolderPath) {
var oFSO;
oFSO =server.createobject ("Scripting.FileSystemObject");
var sparent;
Sparent = Ofso.getparentfoldername (FolderPath);
if (sparent = = "") {return;}
if (!ofso.folderexists (sparent)) {This.createfolder (sparent);}
if (!ofso.folderexists (FolderPath)) {Ofso.createfolder (folderpath);}
OFSO = null;
};

Uploadfile.prototype.getfilepath=function () {
 var ofso,fname,fnamel,i=0;
 ofso = Server.CreateObject ("Scripting.FileSystemObject");
 fname = This.path + this.filename;
 fnamel = This.filename.substr (0,this.filename.lastindexof ("."));
 while (ofso.fileexists (fname)) {
  fname = This.path + Fnamel + "(" + i + ")." + This.extend;
  this.filename = Fnamel + "(" + i + ")." + This.extend
  i++;
&NBSP}
 ofso = null;
 return fname;
};
</script>

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.