我想知道如何通过 django 将上传的文件保存到磁盘。
这是代码
# ...
def spreadsheet_form(request, id = None):
if is_admin_user(request):
instance = get_object_or_404(Spreadsheet, id=id) if id is not None else None
form = SpreadsheetForm(request.POST or None, request.FILES or None, instance=instance)
if form.is_valid():
spreadsheet = form.save(commit=False)
spreadsheet.name = request.POST['name']
spreadsheet.spreadsheet_file = request.FILES['spreadsheet_file']
handle_uploaded_file(request.FILES['spreadsheet_file'])
spreadsheet.save()
return redirect('/spreadsheets/')
return render_to_response("pages/spreadsheet_form.html", {"form": form,"id":id},context_instance=RequestContext(request))
else:
return redirect('/', False)
# ...
def handle_uploaded_file(f):
with open('/tmp/name.txt', 'wb+') as destination:
for chunk in f.chunks():
destination.write(chunk)
目前它返回以下错误:
invalid mode: wb+
Request Method: POST
Request URL: http://0.0.0.0:8000/spreadsheet/new/
Django Version: 1.4.5
Exception Type: IOError
Exception Value:
invalid mode: wb+