Created
February 22, 2020 13:42
-
-
Save adityajn105/8df9f6b04c93538a59830fc83d43d27c to your computer and use it in GitHub Desktop.
Flask Simple File Uploader
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from flask import Flask, request | |
from werkzeug import secure_filename | |
import os | |
app = Flask(__name__) | |
app.config['UPLOAD_FOLDER'] = os.path.join(app.root_path,'uploads/') | |
if not os.path.exists(app.config['UPLOAD_FOLDER']): os.mkdir(app.config['UPLOAD_FOLDER']) | |
def make_page(notification=""): | |
return f""" | |
<html> | |
<head> | |
<title>Upload new File</title> | |
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> | |
</head> | |
<body> | |
<div class="row"> | |
<div class="col-md-6" style="padding: 2%"> | |
{notification} | |
<h3>Upload new File</h3> | |
<form action="/uploader" method="POST" enctype = "multipart/form-data"> | |
<div class="custom-file"> | |
<input type="file" name='file[]' multiple='' class="custom-file-input" id="inputGroupFile01" | |
aria-describedby="inputGroupFileAddon01"> | |
<label class="custom-file-label" for="inputGroupFile01">Browse and Choose one or more Files</label> | |
</div> | |
<br><br> | |
<button type="submit" class="btn btn-default">Upload</button> | |
</form> | |
</div> | |
</div> | |
</body> | |
</html> | |
""" | |
@app.route('/') | |
def upload_file(): | |
return make_page("""<div class='alert alert-warning'> Upload Your File Now!! </div>""") | |
@app.route('/uploader', methods = ['GET', 'POST']) | |
def upload(): | |
if request.method == 'POST': | |
files = request.files.getlist('file[]',None) | |
if files: | |
for file in files: | |
file.save(os.path.join(app.config['UPLOAD_FOLDER'],secure_filename(file.filename))) | |
return make_page(f"""<div class="alert alert-success"> File Uploaded at {app.config['UPLOAD_FOLDER']} </div>""") | |
else: | |
return make_page("""<div class="alert alert-danger"> File Upload Failed!! </div>""") | |
else: | |
return make_page("""<div class='alert alert-warning'> Upload Your File Now!! </div>""") | |
if __name__ == '__main__': | |
app.run( '0.0.0.0' , port = 8000) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment