class ModelFormWithFileField(models.Model):
title = models.CharField(max_length=50)
file = models.FileField(upload_to='test')
def __unicode__(self):
return self.title
比如这是我定义的models类
在数据库是这么存的:
+----+-------+-------------------------------------------+
| id | title | file |
+----+-------+-------------------------------------------+
| 1 | 123 | data/detail.docx |
| 2 | 234 | data/model.txt |
| 3 | 456 | test/10月22PS海报.doc |
| 4 | asd | test/56bfb39bgw1ens2t1aeq.jpg |
| 5 | asd | test/38.0.2125.24.manifest |
+----+-------+-------------------------------------------+
进入django环境的shell
这里导入models,并选一个id为3名字为10月22PS海报.doc的对象x,其中x.file即为我们题目里面的models.FileField数据类型
这里出错是因为python2.x的bug,当然python3.x没这个问题,对策如下:
3行代码搞定
import File来包装一下它,包装过的文件会自动close,这是官方的一句话和demo
The following approach may be used to close files automatically:
>>> from django.core.files import File
# Create a Python file object using open() and the with statement
>>> with open('/tmp/hello.world', 'w') as f:
... myfile = File(f)
... myfile.write('Hello World')
...
>>> myfile.closed
True
>>> f.closed
True
举例两个属性name和size
当然它的所有属性可以用dir(myFile)来获得:
注意,如果要获得文件的url,不能包装它成为File,只能通过
x.file.url获得
其中的site_media是我在settings.py里面设置的MEDIA_URL
-----------------------------------------------------------------分割线-----------------------------------------------------------------
下面说一下如何获得文件类型来return response
>>> from django.core.servers.basehttp import FileWrapper
>>> import mimetypes
>>> wrapper=FileWrapper(x.file)
>>> content_type=mimetypes.guess_type(x.file.url)
>>> print content_type
('application/msword', None)
>>> x.file.closed
False
>>> myFile.closed
False
>>> x.file.close()
>>> myFile.closed
True
#前提是x.file.url做好映射,让django能找到文件,或者我推测它只是通过后缀来确定
在views.py中:
update_to, filename = str(x.file).split('/')
response=HttpResponse(wrapper,mimetype='content_type')
response['Content-Length'] = x.file.size
response['Content-Disposition']="attachment;filename=%s" % filename
return response
搞定