Hello everyone, In this tutorial. we are going to create an API that getting image files to save on the server.
So our requirement is very simple. We are using flask as our framework for creating API. Then we use a simple HTML template where we create a form with a select files field. We send selected files in our API using AjaxJS to save them on the server.
First, create a project directory then create a virtual environment for this project.
So here I use pipenv to create an environment and you can also use virutalenv.
Now install our flask library. Then create a python file. In this minimal start code for flask app.
pipenv install flask
Now create a method for API you can name it whatever you want.
This is our API method.
@app.route('/upload', methods=['POST']) def uploadFile():
We are creating a simple HTML template in a flask and create a method for this to render.
<!doctype html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> <title>Upload File</title> </head> <body> <form id="uploadFileForm" enctype="multipart/form-data"> <div class="form-group"> <label for="file">Select file</label> <input type="file" class="form-control-file" id="file"> </div> <div class="form-group"> <button type="submit" class="btn btn-primary">Send</button> </div> </form> <!-- Optional JavaScript --> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script> </body> </html>
Flask template render method.
@app.route('/') def index(): return render_template('index.html')
Now create a script for getting form data and send it in our API method.
$(document).ready(function() { init(); }); function init() { $('#uploadFileForm').submit(function(e) { e.preventDefault(); sendFile(); }); } function sendFile() { var fileData = $('#file')[0].files; if (fileData.length < 0) { return false; } var formData = new FormData($('#uploadFileForm')[0]); formData.append('selectedFiles', fileData[0]); $.ajax({ type: "POST", url: "/upload", data: formData, contentType: false, processData: false, success: function(response) { // handle results console.info(response); alert(response.message); }, error: function(error) { console.warn(error); alert(error); } }); }
Now handle this data in API point. We create a method definition for Handel files and save files into the upload folder.
Before doing this. We need to set up our upload folder in our project.
First, create a variable for getting the project root path. Then give a folder name. I give "uploads" name to the folder and configure this into our flask app.
app = Flask(__name__) APP_ROOT = os.path.dirname(os.path.abspath(__file__)) UPLOAD_FOLDER = os.path.join(APP_ROOT, 'uploads') app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
Upload folder set now get the file from request and save it into this folder.
@app.route('/upload', methods=['POST']) def uploadFile(): data = {} try: files = request.files['selectedFiles'] # for single file if files: fileName = str(calendar.timegm(time.gmtime())) + '-' + str(files.filename) fileName = secure_filename(fileName) files.save(os.path.join(app.config['UPLOAD_FOLDER'], fileName)) data = {'message': "File Uploaded"} else: data['message'] = "File Not Upload" except Exception as ex: print(ex) data['message'] = ex return jsonify(data)
File saved successfully into our upload folder.
If we send a list of files then we just loop through save all files one by one like this.
@app.route('/upload', methods=['POST']) def uploadFile(): data = {} try: # files = request.files['selectedFiles'] # for single file files = request.files.getlist('selectedFiles') # for multiple files if files: for file in files: fileName = str(calendar.timegm(time.gmtime())) + '-' + str(file.filename) fileName = secure_filename(fileName) file.save(os.path.join(app.config['UPLOAD_FOLDER'], fileName)) data = {'message': "File Uploaded"} else: data['message'] = "File Not Upload" except Exception as ex: print(ex) data['message'] = ex return jsonify(data)
Our flask API created for saving files.
Comments
Post a Comment