RING – How to download files?

Downloading files using the RING is very simple, just by using the DOWNLOAD() function.
SYNTAX:

download(url) #OUTPUT: STRING

And for saving the file, We’ll use the WRITE() function.
SYNTAX:

write(file, content)

The Code Example:

see "Please enter a url to download: " give URL
if not isNULL (URL)
   content = download(URL)
   if not isNULL (content)
      see "File is downloaded, please enter the file name: " give filename
      write(filename, content)
   ok
ok

In the last example, we let the user determine the name of the file, but we will let the program do it by itself, this may be harder.

We can split the url: (Thanks to Gal Zsolt):

list = str2list(substr(trim(url), "/", nl))
reversedList = reverse(list)
filename = reversedList[1] 
see filename #OUTPUT

Or, we can do it manually:

First, We will reverse the url, then we will detect the position of the ‘/’ character from the reversed url, after that, we will use the right() function to cut out the name of the file from the original url from the right direction.

I hope you don’t get lost, but all of this is explained below.

Creating the reverser function:

#SYNTAX: func func_name parameter, parameter, ...
func string_reverser str
	new_str = ''
	for i = len(str) to 1 step -1
		new_str += str[i]
	next
	return new_str

Creating the function to extract the filename:

#SYNTAX: func func_name parameter, parameter, ...
func getURLFileName url, reversedUrl
	postion = substr(reversedUrl, '/') #returns the position of the last '/' character in the original url, which is the first in the reversed one.
	file_name = right(url, postion - 1)
	return file_name

Then we will have the final code like this:

#----------Downloading Section----------
see "Please enter a url to download: " give URL
if not isNULL (URL)
   content = download(URL)
   if not isNULL (content)
   	  reversedURL = string_reverser(url)
	  filename = getURLFileName(url, reversedURL)
      write(filename, content)
   ok
ok

#----------Parsing Section----------
func string_reverser str
	new_str = ''
	for i = len(str) to 1 step -1
		new_str += str[i]
	next
	return new_str

func getURLFileName url, reversedUrl
	postion = substr(reversedUrl, '/')
	file_name = right(url, postion - 1)
	return file_name

I hope you understand the code.

I prefer to let the user determine the file name like in the first example because some URLs doesn’t clearly contain the filename which will cause errors.

amrESSAM.

Advertisements
RING – How to download files?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s