1

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

这是我的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 发送要下载的文件?

4

1 回答 1

2

我使用 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>
于 2013-09-09T11:59:56.957 回答