在 django 中保存 url 中的图像并检查它是否是图像
我在视图中有以下代码:
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()
它工作正常,但我想确保“img_temp”实际上是一个图像。我怎样才能实现这个目标?
编辑:
我找到了解决方案。 python 中有一个名为 imghdr 的模块,可以对文件进行字节级验证以查看它们是否是图像。它可以这样使用:
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()
如果您在此代码中发现任何错误,请告诉我。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
-->它在 Django 1.3 中不起作用,而是使用:
这行代码浪费了我 2 小时
--> it does not work in Django 1.3, instead use:
this line of code waste me 2hours
为什么不直接验证
image_url
是否是图像?Why don't you just validate to see if
image_url
is an image?