【问题标题】:Unable to upload file using django无法使用 django 上传文件
【发布时间】:2011-03-11 01:56:30
【问题描述】:

我无法使用 django 上传文件。当我点击提交按钮时,我得到“此网页不可用。http://127.0.0.1:8000/results 的网页可能暂时关闭,或者它可能已永久移动到新网址。” chrome 中的错误。

对于文件上传 HTTP 查询,相应的网络服务器的日志条目是:

[02/Jul/2010 17:36:06] "POST /results HTTP/1.1" 403 2313

这是表格:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> 

<head> 
 <title>Content Based Image Retrieval System</title>
 <link rel="stylesheet" href="site-content/css/style.css" />
</head>

<body>
 <div><img src="site-content/images/logo.jpg" /> </div>
 <form name="myform" action="results" method="POST" ENCTYPE="multipart/form-data>
  <div align="center">
  <br><br>
  <input type="file" size="25" name="queryImage">
  <br><input type="submit" value="Search"><br>
  </div>
 </form>
</body>

urls.py 中的条目:

(r'^results$',upload_and_search),

处理文件上传的视图:

def upload_and_search(request):
    if request.method != 'POST' or request.FILES is None:
        output = 'Some thing wrong with file uploading'
    handle_uploaded_file(request.FILES['queryImage'])
    output = 'success'
    return HttpResponse(output)

def handle_uploaded_file(f):
    destination = open('queryImage', 'wb+')
    for chunk in f.chunks():
        destination.write(chunk)
    destination.close()

编辑:

我还尝试将目标行 destination = open('queryImage', 'wb+') 更改为 destination = open(os.environ['TMP']+'\\'+filename, 'wb+')。它仍然给出同样的错误。此外,我尝试上传的文件小于 2.5MB。

编辑 2:

我在upload_and_search 的第一行添加了一个打印语句。它没有打印任何内容。即它甚至没有进入该功能。我还通过直接访问 url http://127.0.0.1:8000/results 来检查我的 url 映射是否有问题。它工作正常。我认为服务器配置存在一些问题。我不知道如何配置此服务器或配置什么。我被困住了!我不知道该怎么办。

【问题讨论】:

  • 您尝试在其中写入 queryImage 的目录的权限是什么?
  • 您在 ENCTYPE="multipart/form-data 中也有错误
  • +1 用于在您的第一个问题中提供所有相关信息。看起来有人 阅读了常见问题解答。 ;-)
  • 你能不能在控制台输入一些日志(或者甚至只是print 语句)来查看Django 是否正在访问upload_and_search 视图,以及它是否正确触发了handle_uploaded_file 函数?
  • @Daniel Roseman:请参阅编辑后的问题。

标签: python django


【解决方案1】:

我猜是因为 csrf http://docs.djangoproject.com/en/dev/ref/contrib/csrf/

尝试更改您的来源

<form name="myform" action="results" method="POST" ENCTYPE="multipart/form-data">{% csrf_token %}

生成它的视图

from django.core.context_processors import csrf
from django.shortcuts import render_to_response

def showIndexPage(request):
    c = {}
    c.update(csrf(request))
    return render_to_response("index.html", c)

【讨论】:

    【解决方案2】:

    试试这个:

    filename = f['filename']
    destination = open('%s/%s' % (MEDIA_ROOT, filename), 'wb')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-04-14
      • 1970-01-01
      • 2020-11-29
      • 1970-01-01
      • 2019-07-01
      • 1970-01-01
      • 2022-08-23
      • 1970-01-01
      相关资源
      最近更新 更多