在Django中上传文件的问题

2 投票
2 回答
601 浏览
提问于 2025-04-16 13:00
if request.method == "POST":

我刚开始使用Django框架。我需要上传一个文件,为此我在按照官方文档里的说明操作:http://docs.djangoproject.com/en/dev/topics/http/file-uploads/?from=olddocs
这是我的index.html文件:

    <form action="upload_file" enctype="multipart/form-data" method="POST">
        {% csrf_token %}
        <input type="file" name="upfile" size="30">
        <input type="submit" name="upfile" value= " Upload ">
    </form> 

这是我的views.py文件:

def handle_uploaded_file(f):
    destination = open('/my_path_to_tmp/tmp_files/input_file', 'wb+')
    for chunk in f.chunks():
        destination.write(chunk)
    destination.close()
    if ( f.file_name.endswith("sdf") ):
        return "sdf"
    elif ( f.file_name.endswith("smi") ):
        return "smi"

def upload_file(request):
    if request.method == "POST":
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            file_type = handle_uploaded_file(request.FILES['upfile'])
            return HttpResponseRedirect('calculate', file_type)
    else:
        form = UploadFileForm()
    return render_to_response('upload.html', {'form': form})

这是我的urls.py文件:

urlpatterns = patterns('myapp.views',
    (r'^upload_file$', 'upload_file'),   
    (r'calculate/$', 'calculation'),
)

老实说,我不知道我哪里做错了,但在views.py中的某个条件似乎没有通过。即使我在HTML表单里设置了method="POST"。

有没有人知道这是怎么回事?
非常感谢!

2 个回答

0

你可以在方法开始的时候先输出一下请求的方法,这样可以确认一下... 然后再打印出表单的错误信息。

1

你确定你的表单操作是正确的吗?

难道它不应该是这样的格式吗:

<form action="{% url upload_file %}" enctype="multipart/form-data" method="post">

撰写回答