需要一个使用上传文件处理程序方法上传Django大文件的示例

时间:2016-04-30 19:02:06

标签: python django file-upload django-file-upload

在我的一个django项目中,我正在尝试上传文件。文件可以是视频文件,可以大到20 MB。我试图用django docs中给出的celery和upload_file_handler方法上传它。

我做的是它。

class MyVideo(models.Model):
    user = models.ForeignKey(User)
    video = models.FileField(null=True, blank=True, upload_to="video")

    def __unicode__(self):
        return self.user.username

在forms.py

class VideoForm(forms.ModelForm):
    video = forms.FileField(required=False)

    class Meta:
        model = MyVideo
        exclude = ['user']

    def clean_video(self):
        video = self.cleaned_data['video']
        if video and video._size > (10 * 1024 * 1024):
            raise forms.ValidationError("only 10 MB video is allowed")
        return self.cleaned_data['video']

在View.py

class CreateDigitalAssetsView(LoginRequiredMixin, CreateView):

template_name = "video_create.html"
form_class = VideoForm

def get_success_url(self):
    return reverse("video_url")

def form_valid(self, form):
    user = self.request.user
    video = form.cleaned_data['video']

    if video:
        handle_uploaded_file(video)
        # stick here what to do next.

def handle_uploaded_file(f):
    filename, extension = os.path.splitext(video.name)
    with open('media/video/'+filename, 'wb+') as destination:
        for chunk in f.chunks():
            destination.write(chunk)

在调用handle_uploaded_file之后,我被困在这里做什么。请指导我如何使用hanldle_uploaded_file来保存django模型中的这个书面文件。

1 个答案:

答案 0 :(得分:1)

您需要从handle_uploaded_file函数返回创建文件的路径(相对于/ media root),然后将其保存到模型的视频字段中。

类似于:

def handle_uploaded_file(f):
    filename, extension = os.path.splitext(video.name)
    relative_path = "video/%s" % filename
    full_path = "media/%s" % relative_path
    with open(full_path, 'wb+') as destination:
    for chunk in f.chunks():
        destination.write(chunk)
    return relative_path

def form_valid(self, form):
    ...

    if video:
         relative_path = handle_uploaded_file(video)
         form.instance.video = relative_path
         form.instance.save()