首页 > 解决方案 > 将响应与文件下载和重定向相结合

问题描述

我有一个视图,该 upn 调用,开始下载:

class PrintView(TemplateView): 
    template_name = "proj/listview.html"

    def get(self, request, *args, **kwargs):
        try:
            filepath = TMP.IMG()
            if os.path.exists(filepath):
                with open(filepath, 'rb') as fh:
                    response = HttpResponse(fh.read(), content_type="application/force-download")
                    response['Content-Disposition'] = 'inline; filename=' + os.path.basename(filepath)
                    messages.success(request, "image download started ...")
                    return response
            messages.error(request, "something went wrong!")
            return redirect("index")
        except Exception as e:
            messages.error(request, e)
            return redirect("index")

在我的模板中,我调用了一个带有下载按钮的模式窗口,类似于:

<button id="dl_modal_submit" type="submit"</button>

上面有一些javascript:

let somvar = null;

$('#dlModal').on('show.bs.modal', function (event) {
        
    var button = $(event.relatedTarget); 
    var modal = $(this);
});

document.querySelector('#dl_modal_submit').addEventListener('click', event => {
    const params = { 
        somevar,
    }
    const paramStr = new URLSearchParams(params).toString();
    const dl= `/dl/${somevar}`;
    window.open(dl, "_self");
});

事情是,当我点击我想要的按钮时:

  1. 关闭模态
  2. 开始图片下载
  3. 重定向到索引

这里建议我使用两个视图来执行此操作,但肯定在 javascript 部分中必须有另一种方法来执行此操作?

标签: javascriptdjangodjango-viewsdjango-templates

解决方案


绝对地!

脚本.js:

$('#button').click(function() {

  // close modal:
  $('#modal').hide();

  // download files:
  window.open('the_download_url', '_blank');

  // relocate:
  window.location = 'the_redirect_url';  

});

推荐阅读