Ajax Files to Upload to My Sql
Introduction
Nosotros will create an example here and we volition show y'all how to upload single file or multiple files using AJAX and jQuery along with Python Flask technologies. Y'all can either upload unmarried file using browse button or multiple files using scan button past holding CTRL primal(in Windows Bone) from keyboard while selecting multiple files.
The file or files is/are uploaded into a folder chosen uploads. Make sure this uploads folder exists in the system.
We will also prove success or error messages accordingly.
The benefit of using AJAX technique is your entire folio will non become refreshed on success or error and instead yous will see a detail surface area on the page gets updated.
Related Posts:
- Unmarried File Upload using Python Flask
- Python Flask REST API File Upload Example
- Python Flask Multiple Files Upload Example
- Python Flask REST API Multiple Files Upload
Prerequisites
Python three.7.4, Flask ane.1.1
Creating Projection Directory
Create a projection root directory calledpython-flask-ajax-files-upload as per your chosen location.
We may not mention the projection's root directory proper name in the subsequent sections but we will assume that nosotros are creating files with respect to the project's root directory.
Configuring Application
We volition configure application through flask framework. We volition too define our file upload location and maximum size of all files a user tin can upload.
We should not allow user to upload unlimited size of file due to security reasons or to avoid exhausting server infinite.
Create a file calledapp.py with the beneath code.
from flask import Flask UPLOAD_FOLDER = 'C:/uploads' app = Flask(__name__) app.secret_key = "hugger-mugger key" app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024
Creating Template View File
Nosotros are using template file file-upload.html under templates directory to render the file upload page.
We include jQuery library into<head/>
section of the HTML page. As the example AJAX multiple files upload using Python Flask jQuery suggests and without jQuery or JavaScript engineering science AJAX technique volition not work, jQuery library is required.
You may also utilize plain JavaScript to use AJAX technique but jQuery provides many congenital-in functionalities ad easy to utilise.
We take put the upload field inside<torso/>
tag in HTML page.
Notice hither how theproper name
attribute is used.
We take also usedmultiple
aspect to indicate that we will upload multiple files by property CTRL key (in Windows OS) while selecting files.
We have added below jQuery, AJAX lawmaking immediate after the jQuery library inside<head/>
section of the HTML folio.
WhenUpload
push button is clicked and then nosotros first create a newFormData
object to store the file data.
We get-go recall the file counts and store each file intoFormData
object.
Nosotros then finally ship the file data usingpython-flask-files-upload Residuum endpoint where server side code is written for uploading to the destination directory.
<!doctype html> <html> <caput> <title>Python Flask File(south) Upload Example</championship> <script blazon="text/javascript" src="https://lawmaking.jquery.com/jquery-3.iv.ane.min.js"></script> <script type="text/javascript"> $(certificate).ready(office (e) { $('#upload').on('click', office () { var form_data = new FormData(); var ins = document.getElementById('multiFiles').files.length; if(ins == 0) { $('#msg').html('<span manner="color:red">Select at least one file</bridge>'); render; } for (var x = 0; x < ins; x++) { form_data.append("files[]", certificate.getElementById('multiFiles').files[x]); } $.ajax({ url: 'python-flask-files-upload', // signal to server-side URL dataType: 'json', // what to expect back from server cache: false, contentType: simulated, processData: fake, data: form_data, type: 'post', success: function (response) { // brandish success response $('#msg').html(''); $.each(response, function (key, data) { if(key !== 'message') { $('#msg').suspend(key + ' -> ' + data + '<br/>'); } else { $('#msg').append(data + '<br/>'); } }) }, error: function (response) { $('#msg').html(response.message); // display error response } }); }); }); </script> </head> <trunk> <h2>Python Flask File(due south) Upload - Select file(s) to upload</h2> <dl> <p> <p id="msg"></p> <input type="file" id="multiFiles" name="files[]" multiple="multiple"/> <button id="upload">Upload</button> </p> </dl> </body>
Configuring View and Residual Endpoint
We have divers root (/
) endpoint that will just render the template view file with file upload option on the folio.
We will create Balance endpoint that will be used to upload single or multiple files into the server at a destination folder uploads.
We show a successful bulletin once file or files uploaded successfully or mistake messages depending on the server or client mistake.
If partial file(s) are uploaded then we will come across both success and error messages.
For success messagemessage
is the key in the JSON response.
For fault messages file proper name is the fundamental in the JSON response.
We ascertain a methodallowed_file(filename)
to let user only upload allowed file types.
Only with successful operation we send response status 201 otherwise we ship 400 bad request with fault bulletin.
Create a filemain.py with the below source code.
import os #import magic import urllib.asking from app import app from flask import Flask, flash, asking, redirect, render_template, jsonify from werkzeug.utils import secure_filename ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif']) def allowed_file(filename): render '.' in filename and filename.rsplit('.', one)[1].lower() in ALLOWED_EXTENSIONS @app.road('/') def upload_form(): return render_template('file-upload.html') @app.route('/python-flask-files-upload', methods=['Post']) def upload_file(): # check if the post request has the file role if 'files[]' not in request.files: resp = jsonify({'message' : 'No file part in the asking'}) resp.status_code = 400 return resp files = request.files.getlist('files[]') errors = {} success = False for file in files: if file and allowed_file(file.filename): filename = secure_filename(file.filename) file.save(bone.path.bring together(app.config['UPLOAD_FOLDER'], filename)) success = True else: errors[file.filename] = 'File blazon is not immune' if success and errors: errors['message'] = 'File(s) successfully uploaded' resp = jsonify(errors) resp.status_code = 206 render resp if success: resp = jsonify({'message' : 'Files successfully uploaded'}) resp.status_code = 201 return resp else: resp = jsonify(errors) resp.status_code = 400 return resp if __name__ == "__main__": app.run()
Deploying the Application
Now navigate to the projection'southward root directory using command line tool and execute the commandpython master.py
, your server volition be started on default port5000.
If yous want to change the port and then you can alter the lineapp.run()
toapp.run(port=5001)
, where5001 is the new port.
Testing the Application
Dwelling Page
Striking the URL http://localhost:5000/ in the browser and you will run across output every bit shown below in the image:

Validation Error – No File Selected
When you select no file and effort to upload past clicking on the Upload button.

Fractional Success – Allowed and not-allowed Files
Endeavour to select multiple files (usingCtrl fundamental) and click onUpload button.
So hither ppt file is non immune but pdf file is allowed to be uploaded into the server.
Therefore allowed file types are uploaded and non-allowed file types are not uploaded and displayed with error message including file name so y'all tin be sure which file(s) were non immune to upload.

Success – Allowed Blazon Files But
Try to select multiple files (usingCtrl primal) and click onUpload button.
In this case you will get only success bulletin because all files are allowed in allowed types.

That's all.
Source Lawmaking
download source code
Thanks for reading.
Source: https://roytuts.com/ajax-files-upload-using-python-flask-jquery/
Post a Comment for "Ajax Files to Upload to My Sql"