Reputation: 95
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?
Upvotes: 0
Views: 384
Reputation: 671
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 [email protected] http://127.0.0.1:5000/upload/instructions/newname.txt
Upvotes: 2