写了很简单的一个django上传的例子,可是发现上传的文件和源文件稍微不一样,打开的时候提示“文件损坏”之类的,mp3文件则表现为杂音
主要代码如下:
模版html
<html>
<body>
<form action="#" method="post" enctype="multipart/form-data">
{% csrf_token %}
title: <input name="title" /><br/>
file: <input name="ff" type="file" />
<div><input type="submit" name="post"></div>
</form>
</body>
</html>
处理代码
def handle_upfile(files):
# print 'file name is', files['name']
storefile = open(files.name, 'w')
for chunk in files.chunks():
storefile.write(chunk)
storefile.close()
@csrf_protect
def upload(request):
if request.method == 'POST':
# form = upfileform.UploadForm(request.POST, request.FILES)
print 'check if is_valid'
utils.handle_upfile(request.FILES['ff'])
return HttpResponseRedirect(reverse('fage.views.detail'))
else:
form = upfileform.UploadForm()
return render(request, 'fage/upload.html', {'form': form})
于是上查看django文档,发现一处细微的差别,存放上传文件的打开模式不一样
storefile = open(files.name, 'w')
将之改为
storefile = open(files.name, 'wb+')
问题解决