简体   繁体   中英

How to download the files using vbscript in classic asp

I am working on Classic Asp with VBScript. I am trying to display list of files from a directory with download option. like,在此处输入图像描述

When i click on the download link the corresponding file need to be download for that i have used the following code like,

<html>
<head>
<title> My First ASP Page </title>
</head>
<body>
<%
Dim fso
Dim ObjFolder
Dim ObjOutFile
Dim ObjFiles
Dim ObjFile

'Creating File System Object
Set fso = CreateObject("Scripting.FileSystemObject")

'Getting the Folder Object
Set ObjFolder = fso.GetFolder("F:\karthik")

'Creating an Output File to write the File Names
Set ObjOutFile = fso.CreateTextFile("F:\WindowsFiles.txt")

'Getting the list of Files
Set ObjFiles = ObjFolder.Files

'Writing Name and Path of each File to Output File
Response.Write("<table cellpadding=""4"" cellspacing=""5"" >")
For Each ObjFile In ObjFiles
    Response.Write("<tr><td>"&ObjFile.Name & String(50 - Len(ObjFile.Name), " ")&"</td><td><a href=""#"" language=""VBScript"" onclick=""vbscript:HTTPDownload('"&ObjFile.Path&"','C:\Users\stellent\Downloads\')"">Download</a></td></tr>")
Next
 Response.Write("</table>")
ObjOutFile.Close
%><br>
<script language="vbscript" type="text/vbscript">
Sub HTTPDownload( myURL, myPath )
    ' Standard housekeeping
    Dim i, objFile, objFSO, objHTTP, strFile, strMsg
    Const ForReading = 1, ForWriting = 2, ForAppending = 8

    ' Create a File System Object
    Set objFSO = CreateObject( "Scripting.FileSystemObject" )

    ' Check if the specified target file or folder exists,
    ' and build the fully qualified path of the target file
    If objFSO.FolderExists( myPath ) Then
        strFile = objFSO.BuildPath( myPath, Mid( myURL, InStrRev( myURL, "/" ) + 1 ) )
    ElseIf objFSO.FolderExists( Left( myPath, InStrRev( myPath, "\" ) - 1 ) ) Then
        strFile = myPath
    Else
        WScript.Echo "ERROR: Target folder not found."
        Exit Sub
    End If

    ' Create or open the target file
    Set objFile = objFSO.OpenTextFile( strFile, ForWriting, True )

    ' Create an HTTP object
    Set objHTTP = CreateObject( "WinHttp.WinHttpRequest.5.1" )

    ' Download the specified URL
    objHTTP.Open "GET", myURL, False
    objHTTP.Send

    ' Write the downloaded byte stream to the target file
    For i = 1 To LenB( objHTTP.ResponseBody )
        objFile.Write Chr( AscB( MidB( objHTTP.ResponseBody, i, 1 ) ) )
    Next

    ' Close the target file
    objFile.Close( )
End Sub
</script>
</body>
</html>

It seems you are trying to do this on the server-side using client-side scripting. Here is a better solution that uses server-side ASP to send the file. You will need to split your code over two pages.

Your current script should be replaced with this:

<html> 
<head> 
<title> My First ASP Page </title> 
</head> 
<body> 
<% Dim fso 
Dim ObjFolder 
Dim ObjOutFile 
Dim ObjFiles 
Dim ObjFile 

'Creating File System Object 
Set fso = CreateObject("Scripting.FileSystemObject") 

'Getting the Folder Object 
Set ObjFolder = fso.GetFolder("F:\karthik") 

'Getting the list of Files 
Set ObjFiles = ObjFolder.Files 

'Writing Name and Path of each File to Output File 
Response.Write("<table cellpadding=""4"" cellspacing=""5"" >") 
For Each ObjFile In ObjFiles 
    Response.Write("<tr><td>"&ObjFile.Name & String(50 - Len(ObjFile.Name), " ")&"</td><td><a href=""download.asp?file=" & Server.UrlEncode(ObjFile.Name) & """>Download</a></td></tr>") 
Next 
 Response.Write("</table>") 
%><br> 
</body> 
</html>

Then you need to create another script which I have called download.asp which handles the download:

<%
Dim objConn, strFile
Dim intCampaignRecipientID

strFile = Request.QueryString("file")

If strFile <> "" Then

    Response.Buffer = False
    Dim objStream
    Set objStream = Server.CreateObject("ADODB.Stream")
    objStream.Type = 1 'adTypeBinary
    objStream.Open
    objStream.LoadFromFile("F:\karthik\" & strFile)
    Response.ContentType = "application/x-unknown"
    Response.Addheader "Content-Disposition", "attachment; filename=" & strFile
    Response.BinaryWrite objStream.Read
    objStream.Close
    Set objStream = Nothing

End If
%>

I like this solution, but users can see the downloads in the history, or modify the querystring. This solution can be modified for POST usage this way: in the page code modify the link: <a href="#" onclick="getfile(this);">FileName</a>` and further down

    <form id="frm2dl" action="download.asp" method="post"><input type="hidden" id="file2dl" name="file2dl" value="" /></form>

then in your javascript file get the filename:

    function getfile(obj) {
      var f=obj.innerText;
      $("#frm2dl #file2dl").val(f);
      $("#frm2dl").submit();
    }

alternately you could use a file ID then in the download.asp have a lookup function from ID to filename. Then in the download.asp use request.form("file2dl") instead of request.querystring.

UPDATE: Also, depending on server version you might get the 4MB limit (I have to work with Microsoft-IIS/7.5 on intranet). Therefore for large files the code will not work. Here is my improved version:

Dim strFileName, strFilePath, objFSO, objStream, objFile, intFileSize
Const lChkSize = 524288 ' 500KB - server typical limit is 4MB 
'If session("loggedIn") = True Then ' insert your logon validation code here. bypassed for testing
    strFileName = request.form("file2dl")
    strFilename = Replace(strFilename,"..","") ' prevent parent path navigation - also ensure uploaded files do not contain this sequence
    strFilename = Replace(strFilename,"/","") ' prevent path navigation
    strFilename = Replace(strFilename,"\","") ' filenames should already be cleaned by a previous process
    strFilePath = server.MapPath("/insert your URL absolute sources filepath here/" & strFilename)
    Set objFSO = Server.CreateObject("Scripting.FileSystemObject")
    If objFSO.FileExists(strFilePath) Then
        Set objFile = objFSO.GetFile(strFilePath)
        intFileSize = objFile.Size
        Set objFile = Nothing
        Response.AddHeader "Content-Disposition","attachment; filename=" & strFileName
        Response.ContentType = "application/x-msdownload"
        Response.AddHeader "Content-Length", intFileSize
        Set objStream = Server.CreateObject("ADODB.Stream")
        objStream.Type = 1 'adTypeBinary
        objStream.Open
        objStream.LoadFromFile strFilePath
        Do While Not objStream.EOS And Response.IsClientConnected
            Response.BinaryWrite objStream.Read(lChkSize)
            Response.Flush()
        Loop
        objStream.Close
        Set objStream = Nothing
    Else
        Response.write "Error finding file: " & request.form("file2dl")
    End if
    Set objFSO = Nothing
'End If

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM