Here is the code snippet I'm using right now.
import mimetypes import os import urllib2 import urlparse def filename_from_url(url): return os.path.basename(urlparse.urlsplit(url)[2]) def download_file(url): """Create an urllib2 request and return the request plus some useful info""" name = filename_from_url(url) r = urllib2.urlopen(urllib2.Request(url)) info = r.info() if 'Content-Disposition' in info:
Using:
req, filename, content_type = download_file('http://some.url')
You can then use req as a file-like object and, for example, use shutil.copyfileobj() to copy the contents of the file to a local file. If the MIME type does not matter, simply delete this part of the code.
Since you seem to be lazy, here is the code loading the file directly to the local file:
import shutil def download_file_locally(url, dest): req, filename, content_type = download_file(url) if dest.endswith('/'): dest = os.path.join(dest, filename) with open(dest, 'wb') as f: shutil.copyfileobj(req, f) req.close()
This method is smart enough to use the file name sent by the server if you specify a path ending with a slash, otherwise it uses the destination you specified.
source share