下载文件并在django表单中显示成功消息

时间:2013-09-06 18:54:02

标签: django file jquery download message

在我的表单的提交按钮上,用户可以下载文件。现在我想在表单上添加一条成功消息。

这是我的 send_file函数

def send_file(request, serverFileName, clientFileName):
    wrapper      = FileWrapper(open(serverFileName))
    content_type = mimetypes.guess_type(serverFileName)[0]
    response     = HttpResponse(wrapper,content_type=content_type)
    response['Content-Length']      = os.path.getsize(serverFileName)
    response['Content-Disposition'] = "attachment; filename=%s"%clientFileName
    return response

在我看来......

以下代码(将文件发送到客户端的浏览器):

serverDirectory = settings.MEDIA_ROOT+"/export/"
fileName="europeanActs.csv"
return send_file(request, serverDirectory+fileName, fileName)

现在我尝试添加消息并通过Ajax检索它。 不起作用

serverDirectory = settings.MEDIA_ROOT+"/export/"
fileName="europeanActs.csv"
response_dic['msg']="The acts have been downloaded with success!"
response_dic["msg_class"]="success_msg"
response_dic["file"]=send_file(request, serverDirectory+fileName, fileName)
return HttpResponse(simplejson.dumps(response_dic), mimetype="application/json")

我有一个ajax错误,因为显然response_dic["file"]不是json对象。我想我可以将格式更改为json,但这不是真正的问题。真正的问题是:如何告诉Ajax发送文件下载?

1 个答案:

答案 0 :(得分:1)

我使用iframe解决了这个问题。 如前所述,我将文件返回到 Django视图

serverDirectory = settings.MEDIA_ROOT+"/export/"
fileName="europeanActs.csv"
return send_file(request, serverDirectory+fileName, fileName)

我的 send_file函数

def send_file(request, serverFileName, clientFileName):
    wrapper      = FileWrapper(open(serverFileName))
    content_type = mimetypes.guess_type(serverFileName)[0]
    response     = HttpResponse(wrapper,content_type=content_type)
    response['Content-Length']      = os.path.getsize(serverFileName)
    response['Content-Disposition'] = "attachment; filename=%s"%clientFileName
    return response

然后在 jQuery

//create an iframe in the current form
function iframe_creation()
{
    var iframe = $('<iframe name="postiframe" id="postiframe" style="display: none" />');
    //remove the previous iframe if more than one click on the submit button
    $("#"+$(iframe).attr("id")).remove();
    //append the iframe to the html page
    $("body").append(iframe);
    return iframe;
}

//post a form via an iframe
function post_iframe(iframe, form, link)
{
    var form = $(form);
    form.attr("action", link);
    form.attr("method", "post");
    form.attr("target", $(iframe).attr("id"));
    form.submit();
}

/* submit the export form, download a file and displays success message */
function download_file(form, link)
{
    //create iframe
    iframe=iframe_creation();

    //submit data to iframe
    post_iframe(iframe, form, link)

    //display a success message
    var msg="File successfully sent to download!";
    $("#msg").html(msg);
}

最后以我的 html格式

<button type="button" id="export_button" onclick="javascript:download_file($('#export_form'), '{% url export %}')">EXPORT</button>