通过Curl上传文件

2024-07-07 02:35:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我正试图通过curl将一个文件上传到我的flask应用程序。我没有收到任何错误,但是curl命令最终发送了一个空白文件,或者flask代码没有正确读取它

以下是烧瓶代码:

#Upload a new set of instructions for <ducky_name>. 
@app.route('/upload/instructions/<ducky_name>/', methods = ['POST'])
def upload_Instruction(ducky_name):
    file = request.data
    print("file: ", file)`
    path = os.getcwd() +/files/" + ducky_name + ".txt"
    with open(path, "w") as f:
        f.write(file)
        print("f: ", f)
        f.close()
        return "Success"

下面的curl命令是:

curl -X POST -d @test.txt http://127.0.0.1:5000/upload/instructions/test1/

这是目录树:

├── README.md
└── server_app
    ├── app
    │   ├── __init__.py
    │   ├── __init__.pyc
    │   ├── __pycache__
    │   │   └── __init__.cpython-36.pyc
    │   ├── routes.py
    │   └── routes.pyc
    ├── files
    │   ├── test1
    │   ├── test1.txt
    │   └── test.txt
    ├── __pycache__
    │   └── server_app.cpython-36.pyc
    ├── server_app.py
    └── server_app.pyc

这是file = request.data行的问题吗


Tags: 文件namepytxtappflaskserverinit
1条回答
网友
1楼 · 发布于 2024-07-07 02:35:09

尝试此更改,并让我知道它是否有效

在“app=Flask(name)”后面添加这两行:

UPLOAD_FOLDER = 'files'
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

对路线进行以下更改:

@app.route("/upload/instructions/<ducky_name>", methods=["POST"])
def post_file(ducky_name):
    """Upload a file."""

    file = request.files['secret']
    file.save(os.path.join(app.config['UPLOAD_FOLDER'], ducky_name))


    # Return 201 CREATED
    return "", 201

其中test.txt是要上载的文件的原始名称,newname.txt是上载后要保存为的文件的名称

curl -F  secret=@test.txt  http://127.0.0.1:5000/upload/instructions/newname.txt

相关问题 更多 >