chris
chris

Reputation: 21

Run-time eror '3004' write to file failed when downloading file

im trying to download a file using vba but get "Run-time error '404': Write to file failed." when saving to file

Dim myURL As String
myURL = "http://example.com/file.exe"

Dim WinHttpReq As Object
Set WinHttpReq = CreateObject("Microsoft.XMLHTTP")
WinHttpReq.Open "GET", myURL, False
WinHttpReq.Send

myURL = WinHttpReq.ResponseBody
If WinHttpReq.Status = 200 Then
Set oStream = CreateObject("ADODB.Stream")
oStream.Open
oStream.Type = 1
oStream.Write WinHttpReq.ResponseBody
oStream.SaveToFile "C:\file.exe", 1
oStream.Close
End If

Upvotes: 2

Views: 10813

Answers (3)

rani brooks
rani brooks

Reputation: 1

I was also seeing the runtime error that OP had. My problem, it turns out, was that I already had a file at the target destination with the target file name.

By changing

oStream.SaveToFile "C:\file.exe", 1 '1= no overwrite

to

oStream.SaveToFile "C:\file.exe", 2 '2 = overwrite

the issue was solved. Another solution is to pick a different file destination.

Upvotes: 0

ashleedawg
ashleedawg

Reputation: 21639

You've got something weird going on with the line:

myURL = WinHttpReq.ResponseBody

(You're setting the URL to the HTTP response?)


Download any file from a URL:

Instead, just use this sub as a standalone file-downloading procedure:
(No references requried.)

Sub downloadFile(url As String, fileOutPath As String)

    Dim WinHttpReq As Object, oStream As Object
    Set WinHttpReq = CreateObject("Microsoft.XMLHTTP")
    WinHttpReq.Open "GET", url, False
    WinHttpReq.Send

    If WinHttpReq.Status = 200 Then
        Set oStream = CreateObject("ADODB.Stream")
        oStream.Open
        oStream.Type = 1
        oStream.Write WinHttpReq.ResponseBody
        oStream.SaveToFile fileOutPath, 1 ' 1 = no overwrite, 2 = overwrite
        oStream.Close
    End If

End Sub

Example Usage:

downloadfile "http://ipv4.download.thinkbroadband.com/5MB.zip", "c:\tmp_testFile.zip"

More Information:

Upvotes: 0

SIM
SIM

Reputation: 22440

I've also tried downloading a .exe file and got it working. Try the way I've demonstrated below (it's a working one):

Sub demo()
    Dim HTTP As New XMLHTTP60
    myURL$ = "https://10gbps-io.dl.sourceforge.net/project/exe/Updates/eXe-install-1.04.1.3590.exe"

    With HTTP
        .Open "GET", myURL, False
        .send
    End With

    With CreateObject("ADODB.Stream")
        .Open
        .Type = 1
        .write HTTP.responseBody
        .SaveToFile "D:\Test\Files\" & "3590.exe"  
        .Close
    End With
End Sub

Reference to add to the library:

Microsoft XML, V6.0

Upvotes: 2

Related Questions