Search code examples
javascriptpythondjangoajaxzip

How to download zip file coming as django response through ajax post request?


so, after my ajax post request my Django view return a zip file as a response. I want to download that zip file as soon as the response came. But I don't know what to do. I go through many answers but not worked for me. Right now zip file downloading but when I open it's corrupted. My Django response zip file type is <class '_io.BufferedReader'>.

Ajax Code of Post request

function upload(url) {
    let pdf_file = $('#file_input').get(0).files[0];
    let form_data = new FormData();
    form_data.append("file", pdf_file);
    jQuery.ajax({
        url: url,
        type: "POST",
        data: form_data,
        enctype: 'multipart/form-data',
        contentType: false,
        processData: false,
        success: function (response) {
            var binaryData = [];
            binaryData.push(response);
            var link = document.createElement('a');
            link.href = window.URL.createObjectURL(new Blob(binaryData, {type: "application/zip"}))
            link.download = 'sample.zip';
            document.body.appendChild(link);
            link.click();
            
        },
        error: function (response) {
            loading_btn.classList.add("d-none");
            upload_btn.classList.remove("d-none");
        }
    });
}

ajax Response

enter image description here

Django View

@csrf_exempt
def upload_file(request):
    if request.is_ajax() and request.method == 'POST':
        zip_file = open('/home/deftbox/PycharmProjects/pdf_data_Extractor/test.zip', 'rb')
        return FileResponse(zip_file)

After zipping download when I open my zip file it comes with an error **An error occurred while loading the archive. *

error while opening zip file enter image description here


Solution

  • If you want to download a (binary) file with jQuery.ajax you have to use the xhrFields to set a binary responseType

    function upload(url) {
        let pdf_file = $('#file_input').get(0).files[0];
        let form_data = new FormData();
        form_data.append("file", pdf_file);
        jQuery.ajax({
            url: url,
            type: "POST",
            data: form_data,
            contentType: false,
            processData: false,
            xhrFields:{
                responseType: 'blob'
            },
            success: function (response) {
                var link = document.createElement('a');
                link.href = window.URL.createObjectURL(response)
                link.download = 'sample.zip';
                document.body.appendChild(link);
                link.click();
                
            },
            error: function (response) {
                loading_btn.classList.add("d-none");
                upload_btn.classList.remove("d-none");
            }
        });
    }