我有以下情况:
模型.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)
视图.py
def shapeIng(request): if request.method == 'POST': form = UploadForm(request.POST, request.FILES) if form.is_valid(): form.save()
这样上传的文件是不是自动分块了?如果不是,我想按照文档中的建议将其分块,我尝试了以下方法
模型.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)
视图.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()
我不确定它是否被分块。您能否向我解释一下分块是否在 ModelForm 中是自动的,并可能给我一个工作示例?我是否需要重新定义save()
方法以正常存储“名称”字段并分块“文件”字段?谢谢。