def upload(url, filename=None):
from urllib.request import Request, urlopen
from urllib.parse import urlsplit
import shutil
def getFilename(url,openUrl):
if 'Content-Disposition' in openUrl.info():
# If the response has Content-Disposition, try to get filename from it
cd = dict([x.strip().split('=') if '=' in x else (x.strip(),'')
for x in openUrl.info().split(';')])
if 'filename' in cd:
fname = cd['filename'].strip("\"'")
if fname: return fname
# if no filename was found above, parse it out of the final URL.
return os.path.basename(urlsplit(openUrl.url)[2])
r = urlopen(Request(url))
success = None
try:
filename = filename or "/tmp/%s" % getFilename(url,r)
with open(filename, 'wb') as f:
shutil.copyfileobj(r,f)
success = filename
finally:
r.close()
return success
评论列表
文章目录