Reputation: 303
As we all know the simplest way to upload a file in php is with this code :
<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload File" name="submit">
</form>
I want a method to upload a file with python the simplest as possible, a file from the current directory like this:
import anyuploadmodule
upload(file)
Is there a such module can do this ?
Upvotes: 1
Views: 3288
Reputation: 3471
There isn't anything quite that simple out there, but micro-frameworks like Flask can be lightweight and simple starting points. You'll want to checkout the documentation. Here's a snippet to get you started:
# -*- coding: utf-8 -*-
import os
from flask import Flask, request, redirect, url_for
from werkzeug import secure_filename
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = '/some/path/'
@app.route('/', methods=['GET', 'POST'])
def upload_file():
if request.method == 'POST':
file = request.files['file']
filename = secure_filename(file.filename)
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
return redirect(url_for('uploaded_file', filename=filename))
return '''<!doctype html>
<title>Upload new File</title>
<h1>Upload new File</h1>
<form action="" method=post enctype=multipart/form-data>
<p><input type=file name=file>
<input type=submit value=Upload>
</form>'''
if __name__ == '__main__':
app.run()
Upvotes: 3