首先我并没有找到所谓得“批量上传”接口,倒不如自己写个for循环处理下。
用from上传时要验证表单数据是否合法,然后定位上传路径循环上传即可。
# froms.py
from django import forms
class FileFieldForm(forms.Form):
file_field = forms.FileField(label='选择多个文件',help_text='提示:注意*****',
widget=forms.ClearableFileInput(attrs={'multiple': True, 'class': "bg-info"}))
写那么多算法有什么用,做项目的时候到处找接口,连个for循环都想不起来用
# views.py
def single_upload(f):
file_path = os.path.join(os.path.abspath('.'), 'media/Equipment_pdf', f.name) # 拼装目录名称+文件名称
with open(file_path, 'wb+') as destination: # 写文件word
for chunk in f.chunks():
destination.write(chunk)
destination.close()
def upload(request):
if request.method == 'POST':
form = FileFieldForm(request.POST, request.FILES)
files = request.FILES.getlist('file_field') # 获得多个文件上传进来的文件列表。
if form.is_valid(): # 表单数据如果合法
for f in files:
single_upload(f) # 处理上传来的文件
return HttpResponse('成功')
return HttpResponse('文件上传失败!')
else:
form = FileFieldForm()
return render(request, 'upload.html', locals())
# upload.html