Save image from url in django and checking if it´s an image
I have the following code in a view:
from django.core.files.temp import NamedTemporaryFile
...
image_url = request.POST['url']
name = urlparse(image_url).path.split('/')[-1]
picture = Picture()
picture.user = request.user
img_temp = NamedTemporaryFile(delete=True)
img_temp.write(urllib2.urlopen(image_url).read())
img_temp.flush()
picture.picture.save(name,开发者_运维技巧 File(img_temp))
picture.save()
which works fine, but I want to make sure the "img_temp" is actually an image. How can I achieve this?
EDIT:
I´ve found a solution. Theres a module in python called imghdr that makes byte-level verification to files to see if they are images. It can be used like this:
from django.core.files.temp import NamedTemporaryFile
import imghdr
image_url = request.POST['url']
name = urlparse(image_url).path.split('/')[-1]
picture = Picture()
picture.user = request.user
img_temp = NamedTemporaryFile(delete=True)
img_temp.write(urllib2.urlopen(image_url).read())
img_temp.flush()
to_save = File(img_temp)
to_save.open()
extension = imghdr.what(to_save)
if not extension in ['jpg', 'jpeg', 'png', 'gif']:
to_save.close()
return None
picture.picture.save(name, to_save)
foto.save()
Please let me know if you see any bugs in this code.
img_temp = NamedTemporaryFile(delete=True)
--> it does not work in Django 1.3, instead use:
img_temp = NamedTemporaryFile()
this line of code waste me 2hours
Why don't you just validate to see if image_url
is an image?
精彩评论