Django File Download Progress Bar Guide
Implementing a file download progress bar in Django typically requires using Ajax to send requests and retrieve progress in real-time, then updating the progress bar on the front-end page. Here is a simple implementation process:
- In Django views, the first step is to set the response header for file downloading, informing the browser that it is a file download and specifying the file size.
from django.http import StreamingHttpResponse
from django.core.servers.basehttp import FileWrapper
import os
def download_file(request):
filename = 'path/to/your/file'
wrapper = FileWrapper(open(filename, 'rb'))
response = StreamingHttpResponse(wrapper, content_type='application/octet-stream')
response['Content-Length'] = os.path.getsize(filename)
response['Content-Disposition'] = f'attachment; filename={os.path.basename(filename)}'
return response
- Use Ajax in the front-end to send requests to download files and get real-time progress updates.
<!DOCTYPE html>
<html>
<head>
<title>Download File Progress</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<div id="progress"></div>
<button id="download">Download File</button>
<script>
$(document).ready(function() {
$('#download').click(function() {
var xhr = new XMLHttpRequest();
xhr.open('GET', '/download_file/', true);
xhr.responseType = 'blob';
xhr.onload = function(e) {
if (this.status == 200) {
var blob = new Blob([this.response]);
var url = window.URL.createObjectURL(blob);
var a = document.createElement('a');
a.href = url;
a.download = 'downloaded_file.txt';
a.click();
window.URL.revokeObjectURL(url);
}
};
xhr.onprogress = function(e) {
if (e.lengthComputable) {
var percent = (e.loaded / e.total) * 100;
$('#progress').text(percent.toFixed(2) + '%');
}
};
xhr.send();
});
});
</script>
</body>
</html>
In the code above, an Ajax request is triggered when the user clicks the “Download File” button to download a file and update the download progress in real-time. The progress bar is displayed in the “progress” element on the page.
Please note that the examples above are for reference only, and the specific implementation may vary based on project requirements.