article

Friday, April 2, 2021

AJAX File(s) Upload using Python Flask and jQuery

AJAX File(s) Upload using Python Flask and jQuery

In this tutorial I will show how to upload single file or multiple files using AJAX and jQuery with python flask
app.py
 
#app.py
from flask import Flask, request, render_template, jsonify
import os
#import magic
import urllib.request
from werkzeug.utils import secure_filename

app = Flask(__name__)

UPLOAD_FOLDER = 'static/uploads'
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

app.secret_key = "cairocoders-tutorial101"
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024

ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'])

def allowed_file(filename):
	return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

@app.route('/')
def upload_form():
	return render_template('index.html')
    
@app.route('/upload', methods=['POST'])
def upload_file():
	# check if the post request has the file part
	if 'files[]' not in request.files:
		resp = jsonify({'message' : 'No file part in the request'})
		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(os.path.join(app.config['UPLOAD_FOLDER'], filename))
			success = True
		else:
			errors[file.filename] = 'File type is not allowed'
	
	if success and errors:
		errors['message'] = 'File(s) successfully uploaded'
		resp = jsonify(errors)
		resp.status_code = 206
		return 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(debug=True)
templates/index.hmtl
//templates/index.hmtl
<!doctype html>
<html>
<head>
	<title>AJAX File(s) Upload using Python Flask and jQuery</title>
	<script type="text/javascript" src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
	<script type="text/javascript">
		$(document).ready(function (e) {
			$('#upload').on('click', function () {
				var form_data = new FormData();
				var ins = document.getElementById('multiFiles').files.length;
				
				if(ins == 0) {
					$('#msg').html('<span style="color:red">Select at least one file</span>');
					return;
				}
				
				for (var x = 0; x < ins; x++) {
					form_data.append("files[]", document.getElementById('multiFiles').files[x]);
				}
				
				$.ajax({
					url: '/upload', // point to server-side URL
					dataType: 'json', // what to expect back from server
					cache: false,
					contentType: false,
					processData: false,
					data: form_data,
					type: 'post',
					success: function (response) { // display success response
						$('#msg').html('');
						$.each(response, function (key, data) {							
							if(key !== 'message') {
								$('#msg').append(key + ' -> ' + data + '<br/>');
							} else {
								$('#msg').append(data + '<br/>');
							}
						})
					},
					error: function (response) {
						$('#msg').html(response.message); // display error response
					}
				});
			});
		});
	</script>
</head>
<body>
	<h2>Python Flask File(s) 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>

Related Post