How can I send a zip file on the disk to the client with flask and ajax?












0















I saw this question, but I can't use that answer since the ZipFile is generated in another script. In the flask app, I access that zip file saved on the disk.



        if download_local:
file_name = "adyenfiles.zip"
file_path = os.path.join(app.config["tmp_path"], file_name).replace('\', '/')
logging.info(f"Enviando arquivo: {file_path}")
logging.info(f"FILE_PATH: {file_path}")
response = make_response(send_file(file_path, as_attachment=True, mimetype="application/zip"))
response.headers["Content-Disposition"] = f"attachment;filename={file_name}"
return response


Then on the client:



    $.ajax({
type: "POST",
url: url,
data: $("#manual-download-form").serialize(),
beforeSend: function () {
$("#request-download-progress").show();
displayMessage("Processo de requisição de download iniciado, por favor aguarde.");
},
success: function (response, status, xhr) {
$("#manual-download-form")[0].reset();
$("input[name='date-group']:checked").val("specific");
$("#date-input-area").html(
`
<div class="input-field col s12">
<input id="manual-download-datepicker" name="specific-date" type="text" class="datepicker">
<label for="specific-date">Data*</label>
</div>
`
);
resetDatepicker();
var filename = "";
var disposition = xhr.getResponseHeader('Content-Disposition');
if (disposition && disposition.indexOf('attachment') !== -1) {
var filenameRegex = /filename[^;=n]*=((['"]).*?2|[^;n]*)/;
var matches = filenameRegex.exec(disposition);
if (matches != null && matches[1]) filename = matches[1].replace(/['"]/g, '');
}

var type = xhr.getResponseHeader('Content-Type');
var blob = new Blob([response], { type: "application/zip" });

if (typeof window.navigator.msSaveBlob !== 'undefined') {
// IE workaround for "HTML7007: One or more blob URLs were revoked by closing the blob for which they were created. These URLs will no longer resolve as the data backing the URL has been freed."
window.navigator.msSaveBlob(blob, filename);
} else {
var URL = window.URL || window.webkitURL;
var downloadUrl = URL.createObjectURL(blob);

if (filename) {
// use HTML5 a[download] attribute to specify filename
var a = document.createElement("a");
// safari doesn't support this yet
if (typeof a.download === 'undefined') {
window.location = downloadUrl;
} else {
a.href = downloadUrl;
a.download = filename;
document.body.appendChild(a);
a.click();
}
} else {
window.location = downloadUrl;
}

setTimeout(function () { URL.revokeObjectURL(downloadUrl); }, 100); // cleanup
}
},
complete: function (response, status, xhr) {
$("#request-download-progress").hide();
displayMessage("Se necessário, verifique o diretório para certificar-se de que os arquivos foram baixados.");
},
error: function (response) {
displayMessage(response["responseText"]);
}
});


I get this error when I try to open the zip file (Stating that it can't be open as a zip file):



enter image description here



How can I send a zip file that is saved on the disk to the client?? How do I set it up on flask and generate the blob on the client?










share|improve this question























  • So the whole javascript part is unrelated. You generate the .zip somehow, but can you open the .zip you saved in the file_path location? What happens if you just use send_from_directory instead of trying to make your own response?

    – Joost
    Nov 22 '18 at 12:30











  • It works normally if I use "submit" on the form. The zip works normally. The problem is in the blob being generated.

    – Ericson Willians
    Nov 22 '18 at 12:47











  • Do you want to use the zipped file in the browser, or just let the user download the .zip?

    – Joost
    Nov 22 '18 at 13:22











  • Just download the zip.

    – Ericson Willians
    Nov 22 '18 at 17:17











  • 1) send ajax post 2) generate zip file 3) send download url back from flask to user 4) change windows.location on success to file url

    – Joost
    Nov 22 '18 at 17:25


















0















I saw this question, but I can't use that answer since the ZipFile is generated in another script. In the flask app, I access that zip file saved on the disk.



        if download_local:
file_name = "adyenfiles.zip"
file_path = os.path.join(app.config["tmp_path"], file_name).replace('\', '/')
logging.info(f"Enviando arquivo: {file_path}")
logging.info(f"FILE_PATH: {file_path}")
response = make_response(send_file(file_path, as_attachment=True, mimetype="application/zip"))
response.headers["Content-Disposition"] = f"attachment;filename={file_name}"
return response


Then on the client:



    $.ajax({
type: "POST",
url: url,
data: $("#manual-download-form").serialize(),
beforeSend: function () {
$("#request-download-progress").show();
displayMessage("Processo de requisição de download iniciado, por favor aguarde.");
},
success: function (response, status, xhr) {
$("#manual-download-form")[0].reset();
$("input[name='date-group']:checked").val("specific");
$("#date-input-area").html(
`
<div class="input-field col s12">
<input id="manual-download-datepicker" name="specific-date" type="text" class="datepicker">
<label for="specific-date">Data*</label>
</div>
`
);
resetDatepicker();
var filename = "";
var disposition = xhr.getResponseHeader('Content-Disposition');
if (disposition && disposition.indexOf('attachment') !== -1) {
var filenameRegex = /filename[^;=n]*=((['"]).*?2|[^;n]*)/;
var matches = filenameRegex.exec(disposition);
if (matches != null && matches[1]) filename = matches[1].replace(/['"]/g, '');
}

var type = xhr.getResponseHeader('Content-Type');
var blob = new Blob([response], { type: "application/zip" });

if (typeof window.navigator.msSaveBlob !== 'undefined') {
// IE workaround for "HTML7007: One or more blob URLs were revoked by closing the blob for which they were created. These URLs will no longer resolve as the data backing the URL has been freed."
window.navigator.msSaveBlob(blob, filename);
} else {
var URL = window.URL || window.webkitURL;
var downloadUrl = URL.createObjectURL(blob);

if (filename) {
// use HTML5 a[download] attribute to specify filename
var a = document.createElement("a");
// safari doesn't support this yet
if (typeof a.download === 'undefined') {
window.location = downloadUrl;
} else {
a.href = downloadUrl;
a.download = filename;
document.body.appendChild(a);
a.click();
}
} else {
window.location = downloadUrl;
}

setTimeout(function () { URL.revokeObjectURL(downloadUrl); }, 100); // cleanup
}
},
complete: function (response, status, xhr) {
$("#request-download-progress").hide();
displayMessage("Se necessário, verifique o diretório para certificar-se de que os arquivos foram baixados.");
},
error: function (response) {
displayMessage(response["responseText"]);
}
});


I get this error when I try to open the zip file (Stating that it can't be open as a zip file):



enter image description here



How can I send a zip file that is saved on the disk to the client?? How do I set it up on flask and generate the blob on the client?










share|improve this question























  • So the whole javascript part is unrelated. You generate the .zip somehow, but can you open the .zip you saved in the file_path location? What happens if you just use send_from_directory instead of trying to make your own response?

    – Joost
    Nov 22 '18 at 12:30











  • It works normally if I use "submit" on the form. The zip works normally. The problem is in the blob being generated.

    – Ericson Willians
    Nov 22 '18 at 12:47











  • Do you want to use the zipped file in the browser, or just let the user download the .zip?

    – Joost
    Nov 22 '18 at 13:22











  • Just download the zip.

    – Ericson Willians
    Nov 22 '18 at 17:17











  • 1) send ajax post 2) generate zip file 3) send download url back from flask to user 4) change windows.location on success to file url

    – Joost
    Nov 22 '18 at 17:25
















0












0








0








I saw this question, but I can't use that answer since the ZipFile is generated in another script. In the flask app, I access that zip file saved on the disk.



        if download_local:
file_name = "adyenfiles.zip"
file_path = os.path.join(app.config["tmp_path"], file_name).replace('\', '/')
logging.info(f"Enviando arquivo: {file_path}")
logging.info(f"FILE_PATH: {file_path}")
response = make_response(send_file(file_path, as_attachment=True, mimetype="application/zip"))
response.headers["Content-Disposition"] = f"attachment;filename={file_name}"
return response


Then on the client:



    $.ajax({
type: "POST",
url: url,
data: $("#manual-download-form").serialize(),
beforeSend: function () {
$("#request-download-progress").show();
displayMessage("Processo de requisição de download iniciado, por favor aguarde.");
},
success: function (response, status, xhr) {
$("#manual-download-form")[0].reset();
$("input[name='date-group']:checked").val("specific");
$("#date-input-area").html(
`
<div class="input-field col s12">
<input id="manual-download-datepicker" name="specific-date" type="text" class="datepicker">
<label for="specific-date">Data*</label>
</div>
`
);
resetDatepicker();
var filename = "";
var disposition = xhr.getResponseHeader('Content-Disposition');
if (disposition && disposition.indexOf('attachment') !== -1) {
var filenameRegex = /filename[^;=n]*=((['"]).*?2|[^;n]*)/;
var matches = filenameRegex.exec(disposition);
if (matches != null && matches[1]) filename = matches[1].replace(/['"]/g, '');
}

var type = xhr.getResponseHeader('Content-Type');
var blob = new Blob([response], { type: "application/zip" });

if (typeof window.navigator.msSaveBlob !== 'undefined') {
// IE workaround for "HTML7007: One or more blob URLs were revoked by closing the blob for which they were created. These URLs will no longer resolve as the data backing the URL has been freed."
window.navigator.msSaveBlob(blob, filename);
} else {
var URL = window.URL || window.webkitURL;
var downloadUrl = URL.createObjectURL(blob);

if (filename) {
// use HTML5 a[download] attribute to specify filename
var a = document.createElement("a");
// safari doesn't support this yet
if (typeof a.download === 'undefined') {
window.location = downloadUrl;
} else {
a.href = downloadUrl;
a.download = filename;
document.body.appendChild(a);
a.click();
}
} else {
window.location = downloadUrl;
}

setTimeout(function () { URL.revokeObjectURL(downloadUrl); }, 100); // cleanup
}
},
complete: function (response, status, xhr) {
$("#request-download-progress").hide();
displayMessage("Se necessário, verifique o diretório para certificar-se de que os arquivos foram baixados.");
},
error: function (response) {
displayMessage(response["responseText"]);
}
});


I get this error when I try to open the zip file (Stating that it can't be open as a zip file):



enter image description here



How can I send a zip file that is saved on the disk to the client?? How do I set it up on flask and generate the blob on the client?










share|improve this question














I saw this question, but I can't use that answer since the ZipFile is generated in another script. In the flask app, I access that zip file saved on the disk.



        if download_local:
file_name = "adyenfiles.zip"
file_path = os.path.join(app.config["tmp_path"], file_name).replace('\', '/')
logging.info(f"Enviando arquivo: {file_path}")
logging.info(f"FILE_PATH: {file_path}")
response = make_response(send_file(file_path, as_attachment=True, mimetype="application/zip"))
response.headers["Content-Disposition"] = f"attachment;filename={file_name}"
return response


Then on the client:



    $.ajax({
type: "POST",
url: url,
data: $("#manual-download-form").serialize(),
beforeSend: function () {
$("#request-download-progress").show();
displayMessage("Processo de requisição de download iniciado, por favor aguarde.");
},
success: function (response, status, xhr) {
$("#manual-download-form")[0].reset();
$("input[name='date-group']:checked").val("specific");
$("#date-input-area").html(
`
<div class="input-field col s12">
<input id="manual-download-datepicker" name="specific-date" type="text" class="datepicker">
<label for="specific-date">Data*</label>
</div>
`
);
resetDatepicker();
var filename = "";
var disposition = xhr.getResponseHeader('Content-Disposition');
if (disposition && disposition.indexOf('attachment') !== -1) {
var filenameRegex = /filename[^;=n]*=((['"]).*?2|[^;n]*)/;
var matches = filenameRegex.exec(disposition);
if (matches != null && matches[1]) filename = matches[1].replace(/['"]/g, '');
}

var type = xhr.getResponseHeader('Content-Type');
var blob = new Blob([response], { type: "application/zip" });

if (typeof window.navigator.msSaveBlob !== 'undefined') {
// IE workaround for "HTML7007: One or more blob URLs were revoked by closing the blob for which they were created. These URLs will no longer resolve as the data backing the URL has been freed."
window.navigator.msSaveBlob(blob, filename);
} else {
var URL = window.URL || window.webkitURL;
var downloadUrl = URL.createObjectURL(blob);

if (filename) {
// use HTML5 a[download] attribute to specify filename
var a = document.createElement("a");
// safari doesn't support this yet
if (typeof a.download === 'undefined') {
window.location = downloadUrl;
} else {
a.href = downloadUrl;
a.download = filename;
document.body.appendChild(a);
a.click();
}
} else {
window.location = downloadUrl;
}

setTimeout(function () { URL.revokeObjectURL(downloadUrl); }, 100); // cleanup
}
},
complete: function (response, status, xhr) {
$("#request-download-progress").hide();
displayMessage("Se necessário, verifique o diretório para certificar-se de que os arquivos foram baixados.");
},
error: function (response) {
displayMessage(response["responseText"]);
}
});


I get this error when I try to open the zip file (Stating that it can't be open as a zip file):



enter image description here



How can I send a zip file that is saved on the disk to the client?? How do I set it up on flask and generate the blob on the client?







javascript python jquery flask






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 22 '18 at 11:23









Ericson WilliansEricson Willians

2,86762964




2,86762964













  • So the whole javascript part is unrelated. You generate the .zip somehow, but can you open the .zip you saved in the file_path location? What happens if you just use send_from_directory instead of trying to make your own response?

    – Joost
    Nov 22 '18 at 12:30











  • It works normally if I use "submit" on the form. The zip works normally. The problem is in the blob being generated.

    – Ericson Willians
    Nov 22 '18 at 12:47











  • Do you want to use the zipped file in the browser, or just let the user download the .zip?

    – Joost
    Nov 22 '18 at 13:22











  • Just download the zip.

    – Ericson Willians
    Nov 22 '18 at 17:17











  • 1) send ajax post 2) generate zip file 3) send download url back from flask to user 4) change windows.location on success to file url

    – Joost
    Nov 22 '18 at 17:25





















  • So the whole javascript part is unrelated. You generate the .zip somehow, but can you open the .zip you saved in the file_path location? What happens if you just use send_from_directory instead of trying to make your own response?

    – Joost
    Nov 22 '18 at 12:30











  • It works normally if I use "submit" on the form. The zip works normally. The problem is in the blob being generated.

    – Ericson Willians
    Nov 22 '18 at 12:47











  • Do you want to use the zipped file in the browser, or just let the user download the .zip?

    – Joost
    Nov 22 '18 at 13:22











  • Just download the zip.

    – Ericson Willians
    Nov 22 '18 at 17:17











  • 1) send ajax post 2) generate zip file 3) send download url back from flask to user 4) change windows.location on success to file url

    – Joost
    Nov 22 '18 at 17:25



















So the whole javascript part is unrelated. You generate the .zip somehow, but can you open the .zip you saved in the file_path location? What happens if you just use send_from_directory instead of trying to make your own response?

– Joost
Nov 22 '18 at 12:30





So the whole javascript part is unrelated. You generate the .zip somehow, but can you open the .zip you saved in the file_path location? What happens if you just use send_from_directory instead of trying to make your own response?

– Joost
Nov 22 '18 at 12:30













It works normally if I use "submit" on the form. The zip works normally. The problem is in the blob being generated.

– Ericson Willians
Nov 22 '18 at 12:47





It works normally if I use "submit" on the form. The zip works normally. The problem is in the blob being generated.

– Ericson Willians
Nov 22 '18 at 12:47













Do you want to use the zipped file in the browser, or just let the user download the .zip?

– Joost
Nov 22 '18 at 13:22





Do you want to use the zipped file in the browser, or just let the user download the .zip?

– Joost
Nov 22 '18 at 13:22













Just download the zip.

– Ericson Willians
Nov 22 '18 at 17:17





Just download the zip.

– Ericson Willians
Nov 22 '18 at 17:17













1) send ajax post 2) generate zip file 3) send download url back from flask to user 4) change windows.location on success to file url

– Joost
Nov 22 '18 at 17:25







1) send ajax post 2) generate zip file 3) send download url back from flask to user 4) change windows.location on success to file url

– Joost
Nov 22 '18 at 17:25














0






active

oldest

votes











Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53429889%2fhow-can-i-send-a-zip-file-on-the-disk-to-the-client-with-flask-and-ajax%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























0






active

oldest

votes








0






active

oldest

votes









active

oldest

votes






active

oldest

votes
















draft saved

draft discarded




















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53429889%2fhow-can-i-send-a-zip-file-on-the-disk-to-the-client-with-flask-and-ajax%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Create new schema in PostgreSQL using DBeaver

Deepest pit of an array with Javascript: test on Codility

Costa Masnaga