How to upload a file and show a progress bar in Django?

I wrote code to upload a file in Django as follows:

def upload(request): if request.method == 'POST': form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): handle_uploaded_file(request.FILES['file']) return render_to_response('uploadsuccess.html') else: form = UploadFileForm() return render_to_response('upload.html', {'form': form}) def handle_uploaded_file(f): filename = "/media/Data/static/Data/" + f.name destination = open(filename, 'wb+') for chunk in f.chunks(): destination.write(chunk) destination.close() 

The code works fine for me. However, I do not know how to change this code to show a progress bar on the client side.

My html page looks like this:

 {% extends "index_base.html" %} {% block content %} <script src="/media/js/functions.js" type="text/javascript"></script> <script src="/media/js/jquery.js" type="text/javascript"> </script> <div id="main_container"> {% include "includes/nav.html" %} <!------- Main Contents ----------> <div id="contents_holder"> <div id="contents"> <div id="c_banner"> <span class="main_title">Upload File</span> </div> <div id="setting"> <form name="post" action="/upload.psp/" method="post" enctype="multipart/form-data"> <h2>Upload File</h2></br> <p>{{ form.file.label_tag }}&nbsp;&nbsp;{{ form.file }}</p></br> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <input type="submit" value="Upload" name="uploadButton" /> &nbsp;&nbsp;<input type="button" value="Cancel" name="cancelUploadButton" onclick ="cancelUploadClicked()"/> <input type="hidden" value="title" name="title" id="title" /> </form> </div> </div> </div> </div> <!------- Main Contents Finished ----------> {% endblock %} 

Can someone help me integrate the progress bar with this code?

Thanks in advance.

+5
source share
1 answer

I think you need to send an asynchronous request using Ajax.

The topic is also discussed here: Progress bar of file download with jquery and here: How can I upload files asynchronously?

0
source

Source: https://habr.com/ru/post/1340733/


All Articles