1. 프로젝트 생성

django-admin startproject UploadProject

 

2. APP 생성

django-admin startapp ajaxfilesupload

3. Settings.py 수정

[APP 등록]

INSTALLED_APPS = [
    ...
    ''ajaxfilesupload.apps.AjaxfilesuploadConfig',',
]

 

[template 설정]

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

 

4. template 및 html 생성

 

[files_upload.html]

<!DOCTYPE html>
<html>
    <head>
        <title>Django AJAX Files Upload</title>
    </head>
    <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">Upload</button>
				</p>
			</fieldset>
		</div>
		
		<script src="https://code.jquery.com/jquery-3.6.0.min.js" crossorigin="anonymous"></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]);
					}
					
					csrf_token = $('input[name="csrfmiddlewaretoken"]').val();
					
					//console.log(csrf_token);
					
					form_data.append("csrfmiddlewaretoken", csrf_token);
					
					$.ajax({
						url: 'http://IP:PORT', // 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>

 

5. UploadProject의 urls.py 설정

[urls.py]

from django.contrib import admin
from django.urls import include, path

urlpatterns = [
    path('', include('ajaxfilesupload.urls')),
    path('admin/', admin.site.urls),
]

 

6. ajaxfilesupload APP의 urls.py 설정

 

[urls.py]

from django.urls import path
from django.conf import settings

from . import views

urlpatterns = [
	path('', views.upload_files, name='upload_files'),
	path('upload', views.upload_files, name='upload_files'),
]

 

7. ajaxfilesupload APP의 views.py 설정

[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":
        print('hi')
        return render(request, 'files_upload.html', )
    if request.method == 'POST':
        files = request.FILES.getlist('files[]', None)
        
        #print(files)
        for f in files:
            handle_uploaded_file(f)
        return JsonResponse({'msg':'<span style="color: green;">File successfully uploaded</span>'})
    else:
        return render(request, 'files_upload.html', )

def handle_uploaded_file(f):

    with open(f.name, 'wb+') as destination:
        for chunk in f.chunks():
            destination.write(chunk)

 

8. 실행 및 확인

[실행]

python manage.py runserver 0.0.0.0:8080

 

[확인]

감사합니다.

+ Recent posts