Saving a File from the Internet onto server

How do I download a file from the internet onto the server? (there are all kinds of files.. html / ASP / PHP / PDF / Excel / Word etc.) (Assume that the directory to which it is being written to is write-enabled)

While saving ...
1. I need to check if the file already exists.
2. I need to rename each file with a unique id.

:) SD

Assuming that the URLS are like this and they are all in an array....
LVL 11
Who is Participating?
The database integration part is not there... This one saves with the same filename. It should not be big deal for you to write the DB part...

Response.Buffer = False
Dim url(50)
url(0) = ""
url(0) = ""
url(1) = ""
url(2) = ""
url(3) = ""
url(4) = ""
url(5) = ""
url(6) = ""

Set xmlhttp = Server.CreateObject("Msxml2.ServerXMLHTTP")

For Each Link In url
      Response.Write "Fetching " & Link & "... "
      SaveToFile Link
      Response.Write "Done!<br/>"

Set xmlhttp = Nothing

Sub SaveToFile(strURL)
response.write strurl
   xmlhttp.Open "GET", strURL, False
   If xmlhttp.Status = 200 Then
        strValue = xmlhttp.responseBody
        iSt1 = InStrRev(strURL,"/")+1
        iSt2 = InStr(iSt1,strURL,".")+1
        iEd = InStr(iSt1,strURL,"?")
        If iEd = 0 Then iEd = Len(strURL)+1
        FileName = Mid(strURL,iSt1,iEd-iSt1)
        FileExt = Mid(strURL,iSt2,iEd-iSt2)
        Response.Write FileName & FileExt
        FileName = Server.MapPath(".") & "\" & FileName

        Set oStream = Server.CreateObject("ADODB.Stream")
        oStream.Position = 0
        oStream.Type = 1
        oStream.Write strValue
        oStream.SaveToFile FileName,2
        Set oStream=nothing
    End If
End Sub
Try this - and make sure you have the proper rights to upload files.

<%Response.Buffer = true
Function BuildUpload(RequestBin)
     'Get the boundary
     PosBeg = 1
     PosEnd = InstrB(PosBeg,RequestBin,getByteString(chr(13)))
     boundary = MidB(RequestBin,PosBeg,PosEnd-PosBeg)
     boundaryPos = InstrB(1,RequestBin,boundary)
     'Get all data inside the boundaries
     Do until (boundaryPos=InstrB(RequestBin,boundary & getByteString("--")))
          'Members variable of objects are put in a dictionary object
          Dim UploadControl
          Set UploadControl = CreateObject("Scripting.Dictionary")
          'Get an object name
          Pos = InstrB(BoundaryPos,RequestBin,getByteString("Content-Disposition"))
          Pos = InstrB(Pos,RequestBin,getByteString("name="))
          PosBeg = Pos+6
          PosEnd = InstrB(PosBeg,RequestBin,getByteString(chr(34)))
          Name = getString(MidB(RequestBin,PosBeg,PosEnd-PosBeg))
          PosFile = InstrB(BoundaryPos,RequestBin,getByteString("filename="))
          PosBound = InstrB(PosEnd,RequestBin,boundary)
          'Test if object is of file type
          If PosFile<>0 AND (PosFile<PosBound) Then
               'Get Filename, content-type and content of file
               PosBeg = PosFile + 10
               PosEnd = InstrB(PosBeg,RequestBin,getByteString(chr(34)))
               FileName = getString(MidB(RequestBin,PosBeg,PosEnd-PosBeg))
               'Add filename to dictionary object
               UploadControl.Add "FileName", FileName
               Pos = InstrB(PosEnd,RequestBin,getByteString("Content-Type:"))
               PosBeg = Pos+14
               PosEnd = InstrB(PosBeg,RequestBin,getByteString(chr(13)))
               'Add content-type to dictionary object
               ContentType = getString(MidB(RequestBin,PosBeg,PosEnd-PosBeg))
               UploadControl.Add "ContentType",ContentType
               'Get content of object
               PosBeg = PosEnd+4
               PosEnd = InstrB(PosBeg,RequestBin,boundary)-2
               Value = MidB(RequestBin,PosBeg,PosEnd-PosBeg)
               'Get content of object
               Pos = InstrB(Pos,RequestBin,getByteString(chr(13)))
               PosBeg = Pos+4
               PosEnd = InstrB(PosBeg,RequestBin,boundary)-2
               Value = getString(MidB(RequestBin,PosBeg,PosEnd-PosBeg))
          End If
          UploadControl.Add "Value" , Value    
          UploadRequest.Add name, UploadControl    
End Function

Function getByteString(StringStr)
     For i = 1 to Len(StringStr)
          char = Mid(StringStr,i,1)
          getByteString = getByteString & chrB(AscB(char))
End Function

Function getString(StringBin)
     getString =""
     For intCount = 1 to LenB(StringBin)
          getString = getString & chr(AscB(MidB(StringBin,intCount,1)))
End Function

If request("Action")="1" then
     byteCount = Request.TotalBytes
     RequestBin = Request.BinaryRead(byteCount)
     Set UploadRequest = CreateObject("Scripting.Dictionary")

     If UploadRequest.Item("blob").Item("Value") <> "" Then

          contentType = UploadRequest.Item("blob").Item("ContentType")
          filepathname = UploadRequest.Item("blob").Item("FileName")
          filename = Right(filepathname,Len(filepathname)-InstrRev(filepathname,"\"))
          FolderName = UploadRequest.Item("where").Item("Value")
          Path = server.mappath(".")  & "\"  
          ToFolder = Path & "\" & FolderName
          value = UploadRequest.Item("blob").Item("Value")
          filename = ToFolder & "\" & filename
          Set MyFileObject = Server.CreateObject("Scripting.FileSystemObject")
          Set objFile = MyFileObject.CreateTextFile(filename)
          For i = 1 to LenB(value)
               objFile.Write chr(AscB(MidB(value,i,1)))
          Set objFile = Nothing
          Set MyFileObject = Nothing
     End If
     Set UploadRequest = Nothing

End If%>
<form METHOD="POST" ENCTYPE="multipart/form-data" action="Upload.asp?Action=1" name="form1" id="form1">
<table cellspacing="0" cellpadding="3" width="100%" border="0">
               <b>Select a file to upload:</b><br>
               <input TYPE="file" NAME="blob" value>
               <input TYPE="HIDDEN" NAME="where" value="Images">
          <td align="center">
               <input TYPE="submit" NAME="Upload" Value="Click to Upload">

VB with iNet controls would be a better way of doing this (as compared to ASP with HTTP controls)

How to do part...

- You need a database as files are being saved with a unique ID and not in its real name. The table could have two fields ID,URL. For the ID to be unique, you could write an algorithm for it or let the db autogenerate it.

loop thru the array
  - Check DB to see if the URL is already there: SELECT ID FROM urltable WHERE URL IN (SELECT URL FROM urltable)
  - if the above query returns an empty recordset
     - Use the iNet control to GET each file in the array and save.
  - skip the URL if the recordset not empty
Cloud Class® Course: Amazon Web Services - Basic

Are you thinking about creating an Amazon Web Services account for your business? Not sure where to start? In this course you’ll get an overview of the history of AWS and take a tour of their user interface.

sciber_dudeAuthor Commented:
@ bvinson -

(Correct me if I am wrong) It seems that you have given me code to upload a file from local machine onto the server.

What I want is code for downloading the files from URLs onto the machine where the script is run.

@ fozylet -

I need an ASP solution :(

:) SD

sciber_dudeAuthor Commented:
@ fozylet -

I kinda know the logic as to what is to be done.

In my database, I have the following fields.


I want to code to actually download the files from the URL onto the local machine and rename the file with ID.extension.

(depends on whatever the extension is).

:) SD
You're right, I'm wrong (again)...I completely misread your question.

Sorry for any potential confusion.
sciber_dudeAuthor Commented:
not a problem! Sorry for wasting your effort.

Guess the same thing can be done with XMLHTTP controls (instead of iNet controls)

right now i'm fighting with my deadlines at work (working on a sunday!)
will be happy to write a code for u when i get some free time i.e. if u still need it then ;)
As has been said XmlHttp server or client or ASPHTTP components are the key to doing this. The former is probably the easier for binary files. Your starter for 10 is;EN-US;290761&product=msxml

Minor change...

If Link<>"" Then SaveToFile Link

Also, please take care of declaration/error handling.
My best suggestion is not to use ASP but use VBS. That is because your problem is caused by time-outs, and VBS does not have a timeout on the server it's running on.

Take fozulet's code (it looks ok to me), remove the ASP tags (<% and %>) and replace Server.CreateObject with CreateObject and save the file with the extension .vbs. Then run it from your machine.
sciber_dudeAuthor Commented:
Thanks fozylet and sybe,

I will try these out and get back to you by today evening. Mondays :(

:) SD
sciber_dudeAuthor Commented:
@ fozylet  -
Thanks for the code. That worked perfectly.

@ sybe -
Thanks for the ASP Vs VBS idea. :)

@ mouatts -
Thank you for the link, It was a good read. Now I feel better empowered to approach it.

@ bvinson -
Though your answer was not what i was looking for, I didnt want ur effort to be wasted. Thank you once again.

:) SD
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.