Search code examples
pythondjangofile-uploaduploaduploading

django how to upload folder


I know how to upload multiple files through django, but I have a problem when uploading a folder if there are subfolders in it. The django can't receive subfolders. I found the reason, because browser use '.' to represent a folder, but django can't parse it then stop parsing. Is there an elegant way to fix it?

python code:

def uploader_single(request):
    data = {}
    if request.method == 'POST':
        if True:
            for afile in request.FILES.getlist('file'):
                new_file = UploadFileSingle(file = afile)
                new_file.save()

            return HttpResponseRedirect('')
        else:
            print "form is not valid"
            return HttpResponseRedirect('')
    else:
        print 'not post'

Python code:

class UploadFileSingle(models.Model):
    file        = models.FileField(upload_to='files/%Y/%m/%d', models.FilePath)
    uploaded_at = models.DateTimeField(auto_now_add=True)
    models.FilePathField.recursive = True
    models.FilePathField.allow_folders = True
    updated_at  = models.DateTimeField(auto_now=True)

    def some_folder = FilePathField(path='some_path', recursive=True, allow_files=True, allow_folders=True,)'

HTML code:

<input type="file" name="file" multiple = "true" webkitdirectory="true" directory = "true"/>

Solution

  • There is newer topic which asks the same question and I have tried to answer:

    Django directory upload get sub-directory names

    Basically it is the default behavior of Django if you want to have different behavior you need to write your own upload handlers