Skip to main content
 首页 » 编程设计

python之django上传文件的问题

2025年05月04日26小虾米

我是 django 的新手。我必须上传一个文件并按照官方文档中的说明进行操作: http://docs.djangoproject.com/en/dev/topics/http/file-uploads/?from=olddocs
我的 index.htlm

    <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>  

我的观点.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}) 

我的网址.py

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

真的我不知道我在这里做错了什么,但似乎条件

if request.method == "POST": 

在 views.py 中失败。即使 method="POST"到 html 表单。

有人有想法吗?
非常感谢!

请您参考如下方法:

您确定您的表单操作正确吗?

它不应该是这样的吗:

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