Skip to main content
 首页 » 编程设计

python之django如何上传文件夹

2025年05月04日25zhwl

我知道如何通过 django 上传多个文件,但是如果文件夹中有子文件夹,我在上传文件夹时会遇到问题。 django 无法接收子文件夹。我找到了原因,因为浏览器使用 '.'代表一个文件夹,但 Django 无法解析它然后停止解析。有没有一种优雅的方法来修复它?

python 代码:

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代码:

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代码:

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

请您参考如下方法:

有一个较新的主题问同样的问题,我试着回答:

Django directory upload get sub-directory names

基本上这是 Django 的默认行为,如果你想有不同的行为,你需要编写自己的上传处理程序