Saving a File from the Internet onto server

Posted on 2004-03-20
Last Modified: 2010-08-05
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....
Question by:sciber_dude
  • 5
  • 4
  • 2
  • +2

Assisted Solution

bvinson earned 20 total points
ID: 10642844
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">


Expert Comment

ID: 10642846
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
LVL 11

Author Comment

ID: 10642859
@ 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

LVL 11

Author Comment

ID: 10642866
@ 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

Expert Comment

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

Sorry for any potential confusion.
LVL 11

Author Comment

ID: 10642870
not a problem! Sorry for wasting your effort.

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.


Expert Comment

ID: 10642895
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 ;)
LVL 11

Assisted Solution

mouatts earned 80 total points
ID: 10643394
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


Accepted Solution

fozylet earned 320 total points
ID: 10647955
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

Expert Comment

ID: 10647969
Minor change...

If Link<>"" Then SaveToFile Link

Also, please take care of declaration/error handling.
LVL 28

Assisted Solution

sybe earned 80 total points
ID: 10648023
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.
LVL 11

Author Comment

ID: 10651239
Thanks fozylet and sybe,

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

:) SD
LVL 11

Author Comment

ID: 10680007
@ 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

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Adding items to html ul from on server side. 4 55
How to hide jquery hemiintro in returning user? 1 68
SQL Filter Question 8 79
Server Timeout with Loop 6 38
I would like to start this tip/trick by saying Thank You, to all who said that this could not be done, as it forced me to make sure that it could be accomplished. :) To start, I want to make sure everyone understands the importance of utilizing p…
I was asked about the differences between classic ASP and ASP.NET, so let me put them down here, for reference: Let's make the introductions... Classic ASP was launched by Microsoft in 1998 and dynamically generate web pages upon user interact…
This Micro Tutorial hows how you can integrate  Mac OSX to a Windows Active Directory Domain. Apple has made it easy to allow users to bind their macs to a windows domain with relative ease. The following video show how to bind OSX Mavericks to …
Learn how to create flexible layouts using relative units in CSS.  New relative units added in CSS3 include vw(viewports width), vh(viewports height), vmin(minimum of viewports height and width), and vmax (maximum of viewports height and width).

895 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now