article

Sunday, April 24, 2022

Python Django Upload Multiple Files using jQuery AJAX

Python Django Upload Multiple Files using jQuery AJAX

Bootstrap 5
https://getbootstrap.com/docs/5.0/getting-started/introduction/
https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css

Jquery
https://jquery.com/download/
CDN : jsDelivr CDN
https://www.jsdelivr.com/package/npm/jquery
https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js
testdev/urls.py
//testdev/urls.py
from django.contrib import admin
from django.urls import path
from myapp import views
 
urlpatterns = [
    path('admin/', admin.site.urls),
    path('', views.upload_files, name='upload_files'),
	path('upload', views.upload_files, name='upload_files'),
]
myapp/views.py
 
//myapp/views.py
from django.shortcuts import render
from django.http import JsonResponse
from django.views.decorators.csrf import ensure_csrf_cookie

@ensure_csrf_cookie
def upload_files(request):
    if request.method == "GET":
        return render(request, 'index.html', )
    if request.method == 'POST':
        files = request.FILES.getlist('files[]', None)
        #print(files)
        for f in files:
            handle_uploaded_file(f)
        return JsonResponse({'msg':'<div class="alert alert-success" role="alert">File successfully uploaded</div>'})
    else:
        return render(request, 'index.html', )
			
def handle_uploaded_file(f):  
    with open('myapp/static/upload/'+f.name, 'wb+') as destination:  
        for chunk in f.chunks():  
            destination.write(chunk) 
myapp/templates/index.html
 
//myapp/templates/index.html
{% extends 'base.html' %}

{% block body %}
	<div style="width: 500px; margin: auto;">
		<fieldset name="Multiple Files Upload">
			{% if msg %} {% autoescape off %} {{ msg }} {% endautoescape %} {% endif %}
			<div id="msg"></div>
			<p>
				{% csrf_token %}
				<input type="file" id="multiFiles" name="files[]" multiple="multiple"/>
				<button id="upload" class="btn btn-primary">Upload</button>
			</p>
		</fieldset>
	</div>
{% endblock %}
myapp/templates/base.html
 
//myapp/templates/base.html
<!DOCTYPE html>
<html>
<head>
<title>Python Django Upload Multiple Files using jQuery AJAX - cairocoders</title>
<link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css"/>
</head>
<body>
<div class="container">
    <div class="row">
        <p><h3 class="text-primary">Python Django Upload Multiple Files using jQuery AJAX</h3></p>
        <hr style="border-top:1px dotted #ccc;"/>
        {% block body %}
      
        {% endblock %}
    </div>
</div> 
<script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.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('<div class="alert alert-danger" role="alert">Select at least one file</div>');
			return;
		}
					
		for (var x = 0; x < ins; x++) {
			form_data.append("files[]", document.getElementById('multiFiles').files[x]);
		}
					
		csrf_token = $('input[name="csrfmiddlewaretoken"]').val();
					
		//console.log(csrf_token);
					
		form_data.append("csrfmiddlewaretoken", csrf_token);
					
		$.ajax({
			url: 'upload', // point to server-side URL
			dataType: 'json', // what to expect back from server
			cache: false,
			contentType: false,
			processData: false,
			//data: {'data': form_data, 'csrfmiddlewaretoken': csrf_token},
			data: form_data,
			type: 'post',
			success: function (response) { // display success response
				$('#msg').html(response.msg);
			},
			error: function (response) {
				$('#msg').html(response.message); // display error response
			}
		});
	});
});
</script>
</body>
</html>
Register App myapp
devtest/settings.py
 
//devtest/settings.py
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'myapp',
]
Run : C:\my_project_django\testdev>python manage.py runserver

Related Post