7

通常、サーバーからファイルをダウンロードするのは次のようなものです。

fp = open(file, 'wb')
req = urllib2.urlopen(url)
for line in req:
    fp.write(line)
fp.close()

ダウンロード中に、ダウンロードプロセスを終了する必要があります。プロセスが停止または中断された場合は、ダウンロードプロセスを再開する必要があります。それで、プログラムがダウンロードを一時停止および再開できるようにしたいのですが、どのように実装すればよいですか?ありがとう。

4

2 に答える 2

13

Rangeダウンロードの一時停止/再開を許可するには、Web サーバーが要求ヘッダーをサポートしている必要があります。

Range: <unit>=<range-start>-<range-end>

Rangeクライアントは、指定されたバイトを取得したい場合、ヘッダーを使用してリクエストを行うことができます。次に例を示します。

Range: bytes=0-1024

この場合、サーバーはリクエストを200 OKサポートしていないことを示す応答を返したり、次のように応答したりできます。Range206 Partial Content

HTTP/1.1 206 Partial Content
Accept-Ranges: bytes
Content-Length: 1024
Content-Range: bytes 64-512/1024

Response body.... till 512th byte of the file

見る:

于 2012-09-03T09:18:35.867 に答える
2

Python では、次のことができます。

import urllib, os

class myURLOpener(urllib.FancyURLopener):
    """Create sub-class in order to overide error 206.  This error means a
       partial file is being sent,
       which is ok in this case.  Do nothing with this error.
    """
    def http_error_206(self, url, fp, errcode, errmsg, headers, data=None):
        pass

loop = 1
dlFile = "2.6Distrib.zip"
existSize = 0
myUrlclass = myURLOpener()
if os.path.exists(dlFile):
    outputFile = open(dlFile,"ab")
    existSize = os.path.getsize(dlFile)
    #If the file exists, then only download the remainder
    myUrlclass.addheader("Range","bytes=%s-" % (existSize))
else:
    outputFile = open(dlFile,"wb")

webPage = myUrlclass.open("http://localhost/%s" % dlFile)

#If the file exists, but we already have the whole thing, don't download again
if int(webPage.headers['Content-Length']) == existSize:
    loop = 0
    print "File already downloaded"

numBytes = 0
while loop:
    data = webPage.read(8192)
    if not data:
        break
    outputFile.write(data)
    numBytes = numBytes + len(data)

webPage.close()
outputFile.close()

for k,v in webPage.headers.items():
    print k, "=", v
print "copied", numBytes, "bytes from", webPage.url

ソースを見つけることができます: http://code.activestate.com/recipes/83208-resuming-download-of-a-file/

http dlsでのみ機能します

于 2012-09-03T08:04:54.037 に答える