如何在经典的asp中使用vbscript下载文件

时间:2012-10-17 08:11:24

标签: asp-classic vbscript

我正在使用VBScript处理Classic Asp。我正在尝试使用下载选项显示目录中的文件列表。像,enter image description here

当我点击下载链接时,需要下载相应的文件,因为我使用了以下代码,

<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>

2 个答案:

答案 0 :(得分:11)

您似乎正在尝试使用客户端脚本在服务器端执行此操作。这是一个使用服务器端ASP发送文件的更好的解决方案。您需要将代码分成两页。

您当前的脚本应替换为:

<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>

然后你需要创建另一个我称之为 download.asp 的脚本来处理下载:

<%
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
%>

答案 1 :(得分:0)

我喜欢这种解决方案,但是用户可以在历史记录中查看下载,或修改查询字符串。可以通过以下方式修改此解决方案以用于POST: 在页面代码中修改链接: <a href="#" onclick="getfile(this);">FileName</a>` 并进一步

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

然后在您的javascript文件中获取文件名:

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

或者,您可以使用文件ID,然后在download.asp中具有从ID到文件名的查找功能。 然后在download.asp中使用request.form("file2dl")代替request.querystring。

更新: 另外,根据服务器版本,您可能会获得4MB的限制(我必须在Intranet上使用Microsoft-IIS / 7.5)。因此,对于大文件,该代码将不起作用。这是我的改进版本:

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