简体   繁体   中英

Flask - Uploading a file via Curl

I am trying to upload a file via curl to my flask application. I get no errors, but the curl command ends up sending a blank file, or the flask code doesn't read it properly.

The following is the flask code:

#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"

And the following curl command is:

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

This is the directory tree:

├── 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

Is it a problem with the file = request.data line?

Try this changes and let me know if it works

Add these two lines after your "app = Flask( name )":

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

Make the following changes to your routes:

@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

Where test.txt is the original name of your file that you are uploading and newname.txt is the name of the file you want to be saved as after uploading

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM