You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Nginx+uWSGI+Python3.9环境下无法读取Multipart/Form-data上传文件

文件上传仅获取文件名无法读取内容问题

我为此问题困扰多日,尝试多种方案均未解决。需要读取并处理客户端通过表单上传的文件,但目前仅能获取文件名。试过FieldStorage对象、Werkzeug文件包装器、BytesIO、Webob等多种方式。

以下是相关配置及代码:

uWSGI配置

[uwsgi]
module = test:application
chdir = /var/www/test.ru/python/
plugins = python3
virtualenv = /var/www/test.ru/python/myenv/
max-requests = 5000
processes = 5
threads = 2
master = true
#http = :8080
die-on-term = true
socket = wsgi.sock
chmod-socket = 666
vacuum = true
uid = braimage
gid = braimage
need-app = true
strict = true
limit-post = 52428800

Nginx配置

server {
        listen 80;
        #root /var/www/test.ru/html;
        index index.html index.htm index.nginx-debian.html;
        server_name here goes my external ip;
        charset utf-8;
        client_max_body_size 50M;

        location / {
                root /var/www/test.ru/html;
                try_files $uri $uri/ =404;
        }

        location ~ \.py$ {
                root /var/www/test.ru/python;
                include uwsgi_params;
                uwsgi_pass unix://var/www/test.ru/python/wsgi.sock;
        }
}

HTML表单

<form action="test.py" method="POST" enctype="multipart/form-data>
            <label for="file">Загрузить заполненный шаблон:</label>
            <input type="file" id="myFile" name="myFile" accept=".xls .xlsx">
            <button>обработать файл</button>

test.py代码

import numpy as np
import pandas as pd
from werkzeug.wrappers import Request
import io
import cgi

def application(environ, start_response):
    #body_length = int(environ.get('CONTENT_LENGTH', '0'))
    #request_body = environ['wsgi.input'].read(body_length)
    d = cgi.FieldStorage(environ=environ, fp=environ['wsgi.input'], keep_blank_values=True)
    #file_data = d['myFile'].file.read()
    #filename = d['myFile'].filename
    #df = pd.read_excel(file)
    htmlResponse = [ "<!DOCTYPE html>" ]
    htmlResponse.append("<html>")
    htmlResponse.append("<head>")
    htmlResponse.append('<meta charset="utf-8">')
    htmlResponse.append("</head>")
    htmlResponse.append("<body>")
    #for v in file.items():
    #    htmlResponse.append("<p>environ[] = {str(v)}</p>")
    htmlResponse.append(f"<p>Your value: <span style='color:blue;'>{str(d)}</span></p>")
    #htmlResponse.appendf("<p>Your value: <span style='color:blue;'>{filename}</span></p>")
    htmlResponse.append("</body>")
    htmlResponse.append("</html>")
    start_response("200", [("Content-Type", "text/html")])
    return[ line.encode("utf-8") for line in htmlResponse ]

当前脚本返回结果

Your value: FieldStorage(None, None, [MiniFieldStorage('myFile', 'file.txt')])

Nginx错误日志示例

2022/10/23 16:18:14 [error] 4992#4992: *252 upstream prematurely closed connection while reading response header from upstream, client: my client's ip, server: my server's ip, request: "POST /test.py HTTP/1.1", upstream: "uwsgi://unix://var/www/test.ru/python/wsgi.sock:", host: "my server's ip", referrer: "my servers ip"

内容的提问来源于stack exchange,提问作者braimage

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 01:20:34