码迷,mamicode.com
首页 > 其他好文 > 详细

django fileup-load

时间:2018-10-02 17:50:24      阅读:154      评论:0      收藏:0      [点我收藏+]

标签:for   ever   des   字典   use   put   from   uniq   _for   

文件上传

使用form表单类的上传

forms.py

from django import forms

class UploadFileForm(forms.Form):
    title = forms.CharField(max_length=50)
    file = forms.FileField()

view处理这个form将会从request.FILES中接收file data,它是一个包含所有表单中FileField、ImageField和其他FileField的子类的字典,获取某个文件用request.FILES[‘filename‘]

注:上传文件的form表单必须是POST method,并且enctyoe="ultipart/form-data"。否则request.FILES将为空。

大多数情况下,您只需将文件数据从请求传递到表单,就像绑定上传文件到表单中所描述的那样。例如:

views.py
from django.http import HttpResponseRedirect
from django.shortcuts import render
from .forms import UploadFileForm

# Imaginary function to handle an uploaded file.
from somewhere import handle_uploaded_file

def upload_file(request):
    if request.method == ‘POST‘:
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            handle_uploaded_file(request.FILES[‘file‘])
            return HttpResponseRedirect(‘/success/url/‘)
    else:
        form = UploadFileForm()
    return render(request, ‘upload.html‘, {‘form‘: form})


# 上传文件
def handle_uploaded_file(f):
with open(‘some/file/name.txt‘, ‘wb+‘) as destination:
    for chunk in f.chunks():
        destination.write(chunk)

注:通过UploadedFile.chunks()进行循环而不是使用read()可以确保大文件不会淹没系统的内存。

Handling uploaded files with a model

# models.py

from django.contrib.auth.models import AbstractUser


class UserInfo(AbstractUser):
    nid = models.AutoField(primary_key=True)
    telephone = models.CharField(max_length=11, null=True, unique=True)
    avatar = models.FileField(upload_to=‘avatars/‘, default="avatars/default.png")

# forms.py

from django.http import HttpResponseRedirect
from django.shortcuts import render
from .forms import ModelFormWithFileField

def upload_file(request):
    if request.method == ‘POST‘:
        form = ModelFormWithFileField(request.POST, request.FILES)
        if form.is_valid():
            # file is saved
            form.save()
            return HttpResponseRedirect(‘/success/url/‘)
    else:
        form = ModelFormWithFileField()
    return render(request, ‘upload.html‘, {‘form‘: form})

多文件上传

forms.py
from django import forms

class FileFieldForm(forms.Form):
    file_field = forms.FileField(widget=forms.ClearableFileInput(attrs={‘multiple‘: True}))

重写FormView

# views.py

from django.views.generic.edit import FormView
from .forms import FileFieldForm

class FileFieldView(FormView):
    form_class = FileFieldForm
    template_name = ‘upload.html‘  # Replace with your template.
    success_url = ‘...‘  # Replace with your URL or reverse().

    def post(self, request, *args, **kwargs):
        form_class = self.get_form_class()
        form = self.get_form(form_class)
        files = request.FILES.getlist(‘file_field‘)
        if form.is_valid():
            for f in files:
                ...  # Do something with each file.
            return self.form_valid(form)
        else:
            return self.form_invalid(form)

django fileup-load

标签:for   ever   des   字典   use   put   from   uniq   _for   

原文地址:https://www.cnblogs.com/LTEF/p/9736822.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!