【问题标题】:How to get a file from POST data in python CGI script?如何从 python CGI 脚本中的 POST 数据中获取文件?
【发布时间】:2021-02-09 10:15:04
【问题描述】:

我正在尝试使用 cURL 上传文件并通过 CGI Python3 脚本从另一端检索它并以相同的名称保存。

我当前的 cURL 请求:

curl -X POST --data-binary @file.xlsx http://10.0.0.1/cgi-bin/test.py

如何在python脚本端处理这个文件?

【问题讨论】:

  • 我下面的回答对你有用吗?

标签: python file curl post cgi


【解决方案1】:

在您的情况下,您必须从“stdin”读取二进制数据,这将针对sys.stdin.buffer 发出读取,返回字节:

#!/usr/bin/env python3
import cgi
import cgitb
import sys

cgitb.enable()

data = sys.stdin.buffer.read()
with open(`file.xlsx`, 'wb') as f:
    f.write(data)
print('Content-Type: text/plain\r\n\r\n', end='')
print('Success!')

更新

如果你想发送(上传)一个文件其他数据,那么你需要发送multipart/encoded数据,也就是说你必须使用curl带有-F 选项。例如:

curl -X POST -F "file=@file.xlsx" -F "ip=10.0.0.2" 10.0.0.1/cgi-bin/test.py

那么你的 Python 脚本就变成了:

#!/usr/bin/env python3
import cgi
import cgitb
import os

cgitb.enable()

form = cgi.FieldStorage()
ip = form.getvalue('ip')
fileitem = form['file']
data = fileitem.file.read()
# this is the base name of the file that was uploaded:
filename = os.path.basename(fileitem.filename) # or just use 'file.xlsx' or whatever
with open(filename, 'wb') as f:
    f.write(data)
print('Content-Type: text/plain\r\n\r\n', end='')
print('Success!')

【讨论】:

  • 谢谢!如果我想发送多个参数怎么办,例如: curl -X POST --data-binary "file=@file.xlsx" --data "ip=10.0.0.2" 10.0.0.1/cgi-bin/test.py
猜你喜欢
  • 2019-02-13
  • 2015-08-28
  • 1970-01-01
  • 2013-05-26
  • 1970-01-01
  • 2019-05-12
  • 2015-02-17
  • 1970-01-01
  • 2011-01-29
相关资源
最近更新 更多