如何获取上传文件的文件大小和SHA-1摘要? [英] How to get the filesize and SHA-1 digest of an uploaded file?

查看:270
本文介绍了如何获取上传文件的文件大小和SHA-1摘要?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Django应用中有这个模型:

  class Image(models.Model):
image_file = models.ImageField(
upload_to ='images /',
width_field ='width',
height_field ='height'

width = models.PositiveIntegerField (
blank = True,null = True,
editable = False

height = models.PositiveIntegerField(
blank = True,null = True,
editable = False


sha1 = models.CharField(max_length = 32,blank = True,editable = False)
filesize = models.PositiveIntegerField(blank = True,null = True,editable = False)

我现在可以通过Django管理员网站上传图片。而 width height 属性在上传时自动保存在数据库中,因为特殊的 ImageField 参数。



但是我也希望自动解决上传文件的大小 SHA-1 摘要,并保存这些属性。我该怎么做?

解决方案

已经有一段时间了,但这样的事情应该可以工作:

  import hashlib 
class Image(models.Model):
#...
def save(self,* args ,** kwargs)
super(Image,self).save(* args,** kwargs)
f = self.image_file.open('rb')
hash = hashlib.sha1 ()
如果f.multiple_chunks():
在f.chunks()中的块:
hash.update(chunk)
else:
hash.update f.read())
f.close()
self.sha1 = hash.hexdigest()
self.filesize = self.image_file.size

编辑:
添加了Dan对大块阅读的建议。默认块大小为64KB。


I've got this model in my Django app:

class Image(models.Model):
    image_file = models.ImageField(
        upload_to='images/', 
        width_field='width',
        height_field='height'
    )
    width = models.PositiveIntegerField(
        blank = True, null = True,
        editable = False
    )
    height = models.PositiveIntegerField(
        blank = True, null = True,
        editable = False
    )

    sha1 = models.CharField(max_length=32, blank=True, editable=False)
    filesize = models.PositiveIntegerField(blank=True, null=True, editable=False)

I can now upload images through the Django admin site. And the width and height properties are saved in the database automatically when it's uploaded, because of the special ImageField parameters.

But I'd also like it to automatically work out the uploaded file's size and SHA-1 digest, and save those properties too. How would I do this?

解决方案

Its been a while, but something like this should work:

import hashlib
class Image(models.Model):
#...
    def save(self, *args, **kwargs):
        super(Image, self).save(*args, **kwargs)
        f = self.image_file.open('rb')
        hash = hashlib.sha1()
        if f.multiple_chunks():
           for chunk in f.chunks():
              hash.update(chunk)
        else:    
              hash.update(f.read())
        f.close()
        self.sha1 =  hash.hexdigest()
        self.filesize = self.image_file.size 

EDIT: Added suggestion by Dan on reading by chunk. Default chunk size is 64KB.

这篇关于如何获取上传文件的文件大小和SHA-1摘要?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆