Django ファイルダウンロード進捗バー実装ガイド

Djangoでファイルのダウンロード進行状況を表示するには、通常、Ajaxを使用してリクエストを送信し、進行状況をリアルタイムで取得し、フロントエンドページで進行状況バーを更新する必要があります。以下は簡単な実装手順です。

  1. Djangoのビューで、まずファイルのダウンロードヘッダーを設定する必要があります。これにより、ブラウザにファイルのダウンロードであることとファイルのサイズを設定するように伝えます。
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
  1. フロントエンドページでAjaxを使ってファイルをダウンロードし、ダウンロード進行状況をリアルタイムで取得します。
<!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>

ユーザーが「ファイルをダウンロード」ボタンをクリックすると、Ajaxリクエストがトリガーされ、ファイルをダウンロードし、ダウンロードの進行状況がリアルタイムで取得されます。進捗バーはページ内のprogress要素に表示されます。

上記の例はあくまでも参考までに掲載しており、具体的な実装方法はプロジェクトの要件によって異なる場合がありますので、ご注意ください。

bannerAds