超级简单的下载与进度条 [英] Super simple download with progress bar
问题描述
在AutoHotkey中设置异步下载是一件很痛苦的事情,但是如果您想在下载过程中运行一些代码,例如更新进度条,这是必要的。
Setting up an asynchronous download in AutoHotkey is a pain, but this is is necessary if you want to run some code during the download, like for example updating progress bar.
所以问题是:
有没有一个简单而简单的方式下载一个进度条的文件,而不包括巨大的1000多行库?
So the question is: Is there a short and simple way of downloading a file with a progress bar, without including huge 1000+ lines libraries?
推荐答案
我早就想出了这个代码,你仍然可以在AHK论坛上找到它,但是为什么不和Stackoverflow社区分享:
I came up with that code quite some time ago and you can still find it on the AHK forums, however, why not share it with the Stackoverflow community:
DownloadFile(UrlToFile, SaveFileAs, Overwrite := True, UseProgressBar := True) {
;Check if the file already exists and if we must not overwrite it
If (!Overwrite && FileExist(SaveFileAs))
Return
;Check if the user wants a progressbar
If (UseProgressBar) {
;Initialize the WinHttpRequest Object
WebRequest := ComObjCreate("WinHttp.WinHttpRequest.5.1")
;Download the headers
WebRequest.Open("HEAD", UrlToFile)
WebRequest.Send()
;Store the header which holds the file size in a variable:
FinalSize := WebRequest.GetResponseHeader("Content-Length")
;Create the progressbar and the timer
Progress, H80, , Downloading..., %UrlToFile%
SetTimer, __UpdateProgressBar, 100
}
;Download the file
UrlDownloadToFile, %UrlToFile%, %SaveFileAs%
;Remove the timer and the progressbar because the download has finished
If (UseProgressBar) {
Progress, Off
SetTimer, __UpdateProgressBar, Off
}
Return
;The label that updates the progressbar
__UpdateProgressBar:
;Get the current filesize and tick
CurrentSize := FileOpen(SaveFileAs, "r").Length ;FileGetSize wouldn't return reliable results
CurrentSizeTick := A_TickCount
;Calculate the downloadspeed
Speed := Round((CurrentSize/1024-LastSize/1024)/((CurrentSizeTick-LastSizeTick)/1000)) . " Kb/s"
;Save the current filesize and tick for the next time
LastSizeTick := CurrentSizeTick
LastSize := FileOpen(SaveFileAs, "r").Length
;Calculate percent done
PercentDone := Round(CurrentSize/FinalSize*100)
;Update the ProgressBar
Progress, %PercentDone%, %PercentDone%`% Done, Downloading... (%Speed%), Downloading %SaveFileAs% (%PercentDone%`%)
Return
}
以下是一些示例:
示例1 - 使用进度条下载firefox设置,如果磁盘上已存在,则覆盖它:
DownloadFile("http://download-installer.cdn.mozilla.net/pub/firefox/releases/26.0/win32/en-US/Firefox%20Setup%2026.0.exe", "firefox_setup.exe")
示例2 - 使用进度条下载Autohotkey,如果已存在,请勿覆盖它:
Url = http://ahkscript.org/download/ahk-install.exe
DownloadAs = AutoHotkey_L Installer.exe
Overwrite := False
UseProgressBar := True
DownloadFile(Url, DownloadAs, Overwrite, UseProgressBar)
示例3 - 下载CCleaner设置并打开另存为对话框,要求用户保存文件,如果已存在则覆盖该文件:
FileSelectFile, SaveAs, S, ccsetup410.exe
DownloadFile("http://download.piriform.com/ccsetup410.exe", SaveAs, True, True)
这篇关于超级简单的下载与进度条的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!