[Answered ]-Download a file and display success message in django forms

2๐Ÿ‘

โœ…

I solved the problem using an iframe.
As said previously, I return the file to send in my Django view:

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

My send_file function:

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

Then in 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);
}

Finally in my html form:

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

Leave a comment