Question

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"/>
Was it helpful?

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

OTHER TIPS

I came up with easy solution for this problem.

  • You could get folder name via html and javascript in frontend
  • pass it as a value to hidden form field
  • in backend you can create a directory with that name
  • and upload files in this directory.

HTML

<input type="hidden" name="dir_name" id="id_dir_name">
<input type="file" name="file" onchange="selectFolder(event)" webkitdirectory="" multiple="" required="" directory="" id="id_file">

JS

function selectFolder(e) {
    var theFiles = e.target.files;
    var relativePath = theFiles[0].webkitRelativePath;
    var folder = relativePath.split("/");
    $("#" + id).val(folder[0]);
}

views

directory_name = form.cleaned_data['dir_name']
os.mkdir(os.path.join(settings.MEDIA_ROOT, directory_name))
handle_uploaded_file(request.FILES['file'], directory_name)

you can use django filer

rerfer:https://github.com/stefanfoulis/django-filer

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top