【发布时间】: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脚本端处理这个文件?
【问题讨论】:
-
我下面的回答对你有用吗?
我正在尝试使用 cURL 上传文件并通过 CGI Python3 脚本从另一端检索它并以相同的名称保存。
我当前的 cURL 请求:
curl -X POST --data-binary @file.xlsx http://10.0.0.1/cgi-bin/test.py
如何在python脚本端处理这个文件?
【问题讨论】:
在您的情况下,您必须从“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!')
【讨论】: