我有以下情况:
models.py
class ShapeFile(models.Model):
name = models.SlugField()
file = models.FileField(upload_to=get_upload_path)
def get_upload_path(instance, filename):
return os.path.join("my","custom","path",filename)
views.py
def shapeIng(request):
if request.method == 'POST':
form = UploadForm(request.POST, request.FILES)
if form.is_valid():
form.save()
这样,文件是否自动上传? 如果不是,我想按照文档中的建议将其分块,我尝试了以下
models.py
from django.core.files.storage import default_storage
class ShapeFile(models.Model):
name = models.SlugField()
file = models.FileField(upload_to=get_upload_path)
def get_upload_path_2(filename):
return os.path.join(default_storage.path(''),"my","custom",
"path","%s" % filename)
views.py
from os import makedirs
form os.path import dirname
from django.core.files.storage import default_storage
def shapeIng(request):
if request.method == 'POST':
form = UploadForm(request.POST, request.FILES)
if form.is_valid():
# Split uploaded file into chunks
fileName = request.FILES['file']
filePath = get_upload_path_2(fileName)
handle_uploaded_file(fileName, filePath) # Uploads the file
form.save() # Uploads the file again!!!
def handle_uploaded_file(fileName, filePath):
makedirs(dirname(filePath))
with open(filePath, 'wb+') as destination:
for chunk in fileName.chunks():
destination.write(chunk)
它可以正常工作,但文件存储两次,名称符合Django文档,例如 myFile.zip 和* myFile_1.zip *。与save()
一起存储的那个我不确定它是否被分块。
你能否向我解释一下,如果在模型框架中自动分块,可能会给我一个有效的例子吗?
我是否要重新定义save()
方法以便正常存储“名称”字段并将“文件”字段分块?
感谢。