1

我想知道如何通过 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+
4

1 回答 1

0

如果您的模型Spreadsheet具有FileField,则将文件保存到磁盘所需要做的唯一事情就是传递request.FILES给表单并保存表单:

class Spreadsheet(models.Model):
    file = models.FileField(upload_to="directory/relative/to/MEDIA_ROOT/")
    other_field = ...
    etc.

class SpreadsheetForm(forms.ModelForm):
    class Meta:
        model = Spreadsheet
        fields = ['file', 'other_field', 'etc.']

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()
        return redirect('/spreadsheets/')
    return render_to_response("pages/spreadsheet_form.html", {"form": form,"id":id},context_instance=RequestContext(request))
else:
    return redirect('/', False)
于 2013-07-29T11:55:56.640 回答