我参考Django文档,写了个多文件上传的views.py,但是测试只能保存到最后一个文件,部分代码如下:
views.py:
@csrf_exempt
def test_5(request,template='test_5.html'):
if request.method=='POST':
a = request.FILES.getlist('file')
print a
for files in request.FILES.getlist('file'):
print files
form = UploadFileForm(request.POST, request.FILES)
print form
if form.is_valid():
f = handle_uploaded_file(request.FILES['file'])
print f
title = f[0]
path = f[1].decode('gbk')
upload = list()
upload.append(uploading(filetitle=title, filepath=path))
uploading.objects.bulk_create(upload)
return HttpResponse('上传成功')
else:
form = UploadFileForm()
context = {
'form': form,
}
return render(request, 'test_5.html', context)
为了方便调试,我加了很多print,前端上传三个文件AAAAAAAA.jpg,BBBBBBBBBBB.jpg,CCCCCCCCCCC.gif做测试,输出内容如下:
[<InMemoryUploadedFile: AAAAAAAA.jpg (image/jpeg)>, <InMemoryUploadedFile: BBBBBBBBBBB.jpg (image/jpeg)>, <InMemoryUploadedFile: CCCCCCCCCCC.gif (image/gif)>]
AAAAAAAA.jpg
<tr><th><label for="id_file">File:</label></th><td><input type="file" name="file" required id="id_file" /></td></tr>
(u'CCCCCCCCCCC.gif', 'F:\\django_test\\media\\')
BBBBBBBBBBB.jpg
<tr><th><label for="id_file">File:</label></th><td><input type="file" name="file" required id="id_file" /></td></tr>
(u'CCCCCCCCCCC.gif', 'F:\\django_test\\media\\')
CCCCCCCCCCC.gif
<tr><th><label for="id_file">File:</label></th><td><input type="file" name="file" required id="id_file" /></td></tr>
(u'CCCCCCCCCCC.gif', 'F:\\django_test\\media\\')
不解为什么最后都只保存到了CCCCCCCCCCC.gif。
上传文件处理:
function.py
def handle_uploaded_file(f):
BASE_DIR='F:\django_test'
try:
path = os.path.join(BASE_DIR, 'media\\')
if not os.path.exists(path):
os.makedirs(path)
else:
file_name = str(path + f.name)
destination = open(file_name, 'wb+')
for chunk in f.chunks():
destination.write(chunk)
destination.close()
except Exception, e:
print e
return f.name, path
以上是我的问题,感觉是遍历上传文件的时候出的问题,跪求大神指点。
今天调试好了,问题出在
f = handle_uploaded_file(request.FILES['file'])
上面,request.FILES['file']
包含了三个文件,在之前遍历的for afile in request.FILES.getlist('file')
里面的afile才是单独的流文件,只需要改成f = handle_uploaded_file(afile)
就好了。