【问题标题】:File upload with django使用 django 上传文件
【发布时间】:2011-03-18 21:51:45
【问题描述】:

以下文件上传代码有什么问题。request.FILES['file'] 看起来是空的

型号:

  from django.db import models 
  from django import forms

  class UploadFileForm(forms.Form):
      title = forms.CharField(max_length=50)
      file  = forms.FileField(label="Your file")

观看次数:

def index(request):
  if request.method == 'POST':
   a=request.POST
   logging.debug(a["title"])
   logging.debug(a["file"])
   form = UploadFileForm()
   form = UploadFileForm(request.POST, request.FILES)

  handle_uploaded_file(request.FILES['file'])

  if form.is_valid():
     handle_uploaded_file(request.FILES['file'])

     return HttpResponseRedirect('/Files/')
else:
  form = UploadFileForm()
return render_to_response('Files/index.html', {'form': form})


def handle_uploaded_file(f):
 logging.debug("here1")
 #destination = open('some/file/name.txt', 'wb+')
 destination = open('/tmp', 'wb+')
 for chunk in f.chunks():
   destination.write(chunk)
 destination.close()

模板:

      <form name="lang" action="/test/" method="post">
      <table>
     <tr><td>
     <b> {{ form.file.label_tag }}</b>  {{ form.file}}
     </td></tr>
     <tr><td>
     <input type="hidden" value="title" name="title" id="title" />
     <input type="submit" value="Save" id="Save"/>
     </td></tr>
     </table>
    </form>

【问题讨论】:

    标签: python django django-models django-templates django-views


    【解决方案1】:

    您需要在表单上设置enctype 属性:

    <form enctype="multipart/form-data" method="post" action="/foo/">
    

    Like they say in the docs.

    【讨论】:

      猜你喜欢
      • 2011-06-12
      • 2017-02-14
      • 2010-09-23
      • 1970-01-01
      • 1970-01-01
      • 2021-05-21
      相关资源
      最近更新 更多