在Django中创建文件上传系统

时间:2018-02-25 18:48:11

标签: django python-3.x file-upload

在我的Django应用程序中,我打算创建一个文件上传系统,将用户上传的文件放在data文件夹中。为了做到这一点,我按照在线教程Link 1 Link 2编写了一个简单的应用程序。但它产生了错误

  

PermissionError:[Errno 13]权限被拒绝:'/ data'

项目结构

<project_name>
|--data
|--<app_name>
|--<project_name>
|--manage.py

的index.html

<div class="custom-file">
<input type="file" class="custom-file-input" id="fileupload" name="fileupload" multiple required>
<label class="custom-file-label" for="fileupload">Choose files</label>
</div>

view.py

from django.core.files.storage import FileSystemStorage
from django.views.decorators.csrf import csrf_exempt

@csrf_exempt
def upload(request):
    files = request.FILES.getlist('fileupload')

    fs = FileSystemStorage(location="/data/upload/")

    for fl in files:
        fs.save(fl.name, fl)

settings.py

MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'data')

1 个答案:

答案 0 :(得分:1)

创建多个文件上传应该在表单中处理。

查看Uploading multiple files

forms.py

from django import forms

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

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)