一、Setting准备

Django stores files locally, using the MEDIA_ROOT and MEDIA_URL settings. The examples below assume that you’re using these defaults.

配制参考:http://www.cnblogs.com/yxi-liu/p/8075957.html

 

二、 表结构准备

FileField字段:保存基本的文件

FileField.upload_to 上传文件保存路径
 # file will be saved to MEDIA_ROOT/uploads/2015/01/30 可以包含时间信息
upload = models.FileField(upload_to='uploads/%Y/%m/%d/')
# 更深入的定制通过函数例如:
def user_directory_path(instance, filename):  # filename是原始的名字
    # file will be uploaded to MEDIA_ROOT/user_<id>/<filename>
    return 'user_{0}/{1}'.format(instance.user.id, filename)

class MyModel(models.Model):
    upload = models.FileField(upload_to=user_directory_path)

ImageField在FileField的基础上多了长宽等图像相关的属性

class Car(models.Model):
    name = models.CharField(max_length=255)
    price = models.DecimalField(max_digits=5, decimal_places=2)
    photo = models.ImageField(upload_to='cars')

访问:

>>> car = Car.objects.get(name="57 Chevy")
>>> car.photo
<ImageFieldFile: chevy.jpg>
>>> car.photo.name
'cars/chevy.jpg'
>>> car.photo.path
'/media/cars/chevy.jpg'
>>> car.photo.url
'http://media.example.com/cars/chevy.jpg'

自定制路径:

(通过自定制FilesystemStorage无视Media配制)

from django.db import models
from django.core.files.storage import FileSystemStorage

fs = FileSystemStorage(location='/media/photos')

class Car(models.Model):
    ...
    photo = models.ImageField(storage=fs)

 

 

三、文件访问

>>> from django.core.files import File
# Create a Python file object using open() and the with statement
>>> with open('/path/to/hello.world', 'w') as f:
...     myfile = File(f)
...     myfile.write('Hello World')
>>> myfile.closed
>>> f.closed

 

四、Storage API

默认存储系统为default_storage,在settings中配制DEFAULT_FILE_STORAGE这意味这可以自定制。

>>> from django.core.files.storage import default_storage
>>> from django.core.files.base import ContentFile
>>> path = default_storage.save('/path/to/file', ContentFile('new content'))
>>> path
'/path/to/file'

>>> default_storage.size(path)
11
>>> default_storage.open(path).read()
'new content'

>>> default_storage.delete(path)
>>> default_storage.exists(path)
False

FileSystemStorage类:

location 对应MEDIA_ROOT

base_url对应MEDIA_URL

file_permissions_mode, directory_permissions_mode, get_created_time  用来管理权限和时间

 

Storage类方法详见:https://docs.djangoproject.com/en/2.0/ref/files/storage/