2010-06-04 36 views
15

Tengo un script VBS que genera una url para descargar un archivo desde un servidor en mi red. Ahora necesito descargar el archivo a "C: \ rWallpaper \ wallpaper.png", la URL se almacena en la variable "url"Descargar un archivo con VBS

Me gustaría que funcionara algo así como wget en Linux, solo descargue y guarde el archivo a una ubicación especificada.

Respuesta

29

Puede descargar usando XMLHTTP y aprovechar una transmisión ADO para escribir los datos binarios;

dim xHttp: Set xHttp = createobject("Microsoft.XMLHTTP") 
dim bStrm: Set bStrm = createobject("Adodb.Stream") 
xHttp.Open "GET", "http://bla.com/xxx.png", False 
xHttp.Send 

with bStrm 
    .type = 1 '//binary 
    .open 
    .write xHttp.responseBody 
    .savetofile "c:\temp\xxx.png", 2 '//overwrite 
end with 
+0

Esto funciona y me ha ayudado mucho, pero hay que especificar el nombre de destino. El problema es si quieres usar el nombre de archivo original sugerido por el servidor. – Racky

+7

@Racky después de '.send' (en caso de que el servidor lo considere así) el nombre de archivo sugerido es después del' filename = 'token disponible a través de' hdr = xHttp.getResponseHeader ("Content-Disposition") ' –

6

La respuesta anterior arrojó el error Write to file failed. Code: 800A0BBC para mí, sin embargo, esto funcionó:

HTTPDownload http://www.emagcloud.com/europeansealing/FSA_ESA_Compression_Packing_Technical_Manual_v3/pubData/source/images/pages/page10.jpg", "C:\" 

Dónde

Sub HTTPDownload(myURL, myPath) 
' This Sub downloads the FILE specified in myURL to the path specified in myPath. 
' 
' myURL must always end with a file name 
' myPath may be a directory or a file name; in either case the directory must exist 
' 
' Written by Rob van der Woude 
' http://www.robvanderwoude.com 
' 
' Based on a script found on the Thai Visa forum 
' http://www.thaivisa.com/forum/index.php?showtopic=21832 

    ' 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 

+0

Si la respuesta aceptada fallado con ese error específico, el problema son los permisos para escribir en la carpeta, que no es difícil de resolver. – Lankymart

+1

Tienes razón, y lo resolví utilizando el código provisto. –

+1

Su método es muy lento cuando el tamaño del archivo es grande (por ejemplo, 400k pdf, utilicé 20 segundos para descargar) la respuesta marcada que solo usa 2 segundos para descargar el mismo archivo. –

0

Esta publicación es antigua, pero el error en la respuesta del código fisrt es que necesita privilegios para escribir en C :. Pruebe en el escritorio o% temp%, funciona.

3

Además de Alex K respuesta, utilizó la siguiente si ayuda a alguien:

Definir objeto

Set objWinHttp = CreateObject("WinHttp.WinHttpRequest.5.1") 

llamada Enlace de descarga con un archivo (imagen en nuestro caso)

URL = "https://www.grupya.com/public/assets/img/logo.png" 
objWinHttp.open "GET", URL, False 
objWinHttp.send "" 

Guarde los datos binarios en el disco

SaveBinaryData "c:\temp\my.png",objWinHttp.responseBody 

Función SaveBinaryData

Function SaveBinaryData(FileName, Data) 

' adTypeText for binary = 1 
Const adTypeText = 1 
Const adSaveCreateOverWrite = 2 

' Create Stream object 
Dim BinaryStream 
Set BinaryStream = CreateObject("ADODB.Stream") 

' Specify stream type - we want To save Data/string data. 
BinaryStream.Type = adTypeText 

' Open the stream And write binary data To the object 
BinaryStream.Open 
BinaryStream.Write Data 

' Save binary data To disk 
BinaryStream.SaveToFile FileName, adSaveCreateOverWrite 

End Function 
+0

Funciona como un encanto; Toda'a –