Download file with callback

BlitzMax Forums/BlitzMax Programming/Download file with callback

JoshK(Posted 2006) [#1]
The command CopyFile() can download a file from the internet and copy it to the user's hard drive. I want to write a new copyfile function with a callback, so that the download progress can be displayed:


The problem is that a URL opened with ReadStream() has an unknown size. If I pre-cache the file with ReadFile(), the entire file is loaded, so I know the size, but I can't display the progress until after the actual file data is already downloaded.

How can I find out the size of a file on the internet, or a stream opened with ReadStream()?


Kev(Posted 2006) [#2]
a post by Yan sometime back, this will return the files size without downloading.

Print HTTPFileSize("http://YOUR URL TO FILE") + " Bytes"

End


Function HTTPFileSize(url$)
	url$ = url$.Replace("http://", "")
	Local slashPos = url$.Find("/"), host$, file$
	
	If slashPos <> -1
		host$ = url$[..slashPos]
		file$ = url$[slashPos..]
	Else
		Return -1
	EndIf
	
	Local stream:TStream=OpenStream("tcp::" + host$, 80)
	If Not stream Then Return -1	
	
	stream.WriteLine "HEAD " + file$ + " HTTP/1.0"
	stream.WriteLine "Host: " + host$
	stream.WriteLine ""
	
	While Not Eof(stream)
		Local in$ = stream.ReadLine()

		If in$.Find("Content-Length:") <> -1
			stream.Close()
			Return Int(in$[in$.Find(":") + 1..].Trim())
		EndIf	
	Wend
	
	stream.Close()
	Return -1		
End Function



JoshK(Posted 2006) [#3]
Okay, this works. Now I just need to figure out how to stop the transfer if the connection is broken:




JoshK(Posted 2006) [#4]
Now this is cool. I fixed it so if you the connection is list, the function just returns false.


And this will automatically detect and download app updates: