我知道如何通过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 code:
<input type="file" name="file" multiple = "true" webkitdirectory="true" directory = "true"/>
答案 0 :(得分:1)
有更新的主题提出同样的问题,我试图回答:
Django directory upload get sub-directory names
如果您想要编写自己的上传处理程序所需的不同行为,基本上它是Django的默认行为
答案 1 :(得分:0)
我想出了解决这个问题的简便方法。
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]);
}
观看次数
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)
答案 2 :(得分:-2)
你可以使用django filer