使用curl将文件上传到python flask服务器

ano*_*123 18 python curl flask

我正在尝试使用curl和python flask将文件上传到服务器.下面我有我如何实现它的代码.关于我做错了什么的任何想法.

curl -i -X PUT -F name=Test -F filedata=@SomeFile.pdf "http://localhost:5000/" 

@app.route("/", methods=['POST','PUT'])
def hello():
    file = request.files['Test']
    if file and allowed_file(file.filename):
        filename=secure_filename(file.filename)
        print filename

    return "Success"
Run Code Online (Sandbox Code Playgroud)

以下是服务器发回的错误

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<title>400 Bad Request</title>
<h1>Bad Request</h1>
<p>The browser (or proxy) sent a request that this server could not understand.</p>
Run Code Online (Sandbox Code Playgroud)

提前致谢.

mat*_*ata 17

你的curl命令意味着你要传输两个表单内容,一个名为call的文件filedata和一个名为的表单字段name.所以你可以这样做:

file = request.files['filedata']   # gives you a FileStorage
test = request.form['name']        # gives you the string 'Test'
Run Code Online (Sandbox Code Playgroud)

request.files['Test']不存在.


Esb*_*rdt 9

我在让它工作时遇到了很多问题,所以这里有一个非常明确的解决方案:

这里我们制作一个简单的 Flask 应用程序,它有两条路线,一条用于测试应用程序是否工作(“Hello World”),一条用于打印文件名(以确保我们获取文件)。

from flask import Flask, request
from werkzeug.utils import secure_filename

app = Flask(__name__)

@app.route("/")
def hello_world():
    return "Hello World"

@app.route("/print_filename", methods=['POST','PUT'])
def print_filename():
    file = request.files['file']
    filename=secure_filename(file.filename)   
    return filename

if __name__=="__main__":
    app.run(port=6969, debug=True)
Run Code Online (Sandbox Code Playgroud)

首先我们测试是否可以联系该应用程序:

curl http://localhost:6969
>Hello World
Run Code Online (Sandbox Code Playgroud)

现在让我们发布一个文件并获取它的文件名。我们用“file=”来引用文件,因为“request.files['file']”指的是“文件”。这里我们进入一个目录,其中有一个名为“test.txt”的文件:

curl -X POST -F file=@test.txt http://localhost:6969/print_filename
>test.txt
Run Code Online (Sandbox Code Playgroud)

最后我们要使用文件路径:

curl -X POST -F file=@"/path/to/my/file/test.txt" http://localhost:6969/print_filename
>test.txt
Run Code Online (Sandbox Code Playgroud)

现在我们已经确认我们实际上可以获取该文件,然后您可以使用标准 Python 代码对它执行任何您想要的操作。