无法使用Django上传文件

2 投票
2 回答
1011 浏览
提问于 2025-04-16 00:44

我在使用Django上传文件时遇到了问题。当我点击提交按钮时,Chrome浏览器显示“此网页不可用。网页 http://127.0.0.1:8000/results 可能暂时无法访问,或者可能已经永久移动到新的网址。”

关于文件上传的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 的第一行添加了一个打印语句,但没有任何输出。也就是说,它根本没有进入这个函数。我还直接访问了网址 http://127.0.0.1:8000/results,发现它可以正常工作。我觉得服务器配置可能有问题,但我不知道该如何配置这个服务器,也不知道要配置什么。我现在很困惑,不知道该怎么办。

2 个回答

0

试试这个:

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

我想这可能是因为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)

撰写回答