How to handle the forced download of zip file using JQuery - javascript

I'm using a REST API with POST data. I'm creating a zip file and doing a forced download. I need to call that API by sending the required POST data using JQuery, which should then get the download. How can I achieve this?

You could do this :
HTML:
<input type="button" class="list" value="Download ZipFile" id="download"/>
JS :
$("#download").click(function(){
//this is the data when you send your request
var data = { yourKey1 :'something1', yourKey2:'something2'};
// this is a fake response that we are assumming you got from ajax's response inside success call back
var response = {fileName:'yourFileName.zip' ,filePath : 'YouFilePath'};
$.ajax({
type: "POST",
url: 'yourURL',
data: data,
success: function(response) {
download(response);
}
});
});
var download = function (data){
var link = document.createElement('a');
link.href = data.filePath + data.fileName ;
//below you can define a new name
link.download = data.fileName;
document.body.appendChild(link);
link.click();
}
Example : https://jsfiddle.net/3yjt4Lah/8/

Related

Create PDF with Ajax

I am using FPDF to create my report.
$pdf = new Report('P','mm','A4', $_POST);
$pdf->AddPage();
$pdf->Output('file.pdf','I');
And I use ajax to make requisition to the PHP.
$.ajax({
type: 'POST',
url: '../reports/report.php',
data: { id: id }
}).done(function(data){
window.open(data);
})
I want to show the report in a new tab
I think you should success key. So it would be something like this
$.ajax({
type: 'POST',
url: '../reports/report.php',
data: { id: id },
success: function(data){
var blob = new Blob([data]);
window.open(URL.createObjectURL(blob));
}
})
Resolved:
I did the different way:
In my report PHP, I generate one temporay file, passing the parameter 'F'.
$pdf->Output('file.pdf','F');
In Jquery Ajax I opne the file, rather than open the data retorned of ajax request.
$.ajax({
type: 'POST',
url: '../reports/report.php',
data: { id: id }
}).done(function(data){
var fileName = "file.pdf";
$('#modalRel').modal('show');
var object = "<object data=\"{FileName}\" type=\"application/pdf\" width=\"500px\" height=\"300px\">";
object += "If you are unable to view file, you can download from here";
object += " or download <a target = \"_blank\" href = \"http://get.adobe.com/reader/\">Adobe PDF Reader</a> to view the file.";
object += "</object>";
object = object.replace(/{FileName}/g, "../Files/" + fileName);
$("#body-rel").html(object);
})
I hope to have helped who one day to need.

How to read image using input type=file and send this image as a POST request

I am trying to read an image using HTML input of type = 'File'. After the user selects the file, i wish to make a POST request to a particular URL. This POST request should have the image selected by the user.
I have looked into jQuery Ajax calls without any success. The link which I am trying to hit expects an image as byte array.
Try this:
html:
<input id="pic" type="file" name="pic" />
<button id="upload">Upload</button>
Jquery:
$('#upload').on('click', function() {
var file_data = $('#pic').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
$.ajax({
url : 'upload.php', // point to server-side PHP script
dataType : 'text', // what to expect back from the PHP script, if anything
cache : false,
contentType : false,
processData : false,
data : form_data,
type : 'post',
success : function(output){
alert(output); // display response from the PHP script, if any
}
});
});

PDF File download from AJAX Post success callback

When I try to link to a data-generated file that I've set up to be rendered as a PDF document, this works to open a PDF document in a new window, but only for small sets of data:
window.open(myUrl + params, "_blank", "menubar=no,status=no");
I need it to work for something like this so I can make my PDF compatible with larger data sets. I tried passing the params in the data section of the ajax request but it doesn't work for PDF documents only. It works for Word and Excel documents. When I try the same thing as a PDF, it returns a download to a broken PDF object.
$.ajax({
type:"POST",
async:true,
url: myUrl,
data: params,
success: function(result,status,jqhxr) {
var blob=new Blob([result]);
var link=document.createElement('a');
link.setAttribute('target','_blank');
link.href=window.URL.createObjectURL(blob);
link.download="PreviewProposalAsPdf.pdf";
link.click();
}
});
What do I need to do to get this to render a PDF correctly? Ideally I'd like to navigate directly to the PDF page in a new window, but I will settle for a clickable file download. Please post the full solution directly if possible. I've spent a ton of time on this and my time is now running short.
I looked for the solution on other questions but none of the solutions worked. In some cases, what I'm already trying was posted as a solution. Please help.
Thanks
The result you get back from using jQuery ajax is plain text and can lead to "out of range" for downloading binary as text and not as arrayBuffer or blob. jQuery don't support responseType in any way (that i know of)
So you need to rely on xhr or fetch to get it as a blob to get the content right. Otherwise you will get corrupt data
Here is an example of using the new fetch api and FileSaver
function saveAs(blob, filename){
if(navigator.msSaveOrOpenBlob)
return navigator.msSaveOrOpenBlob(blob, filename)
var link = document.createElement('a')
link.href = window.URL.createObjectURL(blob)
link.download = filename
link.click()
}
fetch(myUrl, {
method: 'post',
body: JSON.stringify(params)
headers: {
'Content-Type': 'application/json;charset=UTF-8'
}
})
.then(res => res.blob())
.then(blob => saveAs(blob, 'PreviewProposalAsPdf.pdf'))
// EXAMPLE USING XHR
var req = new XMLHttpRequest
req.open('GET', myUrl, true)
req.responseType = 'blob'
req.onload = function() {
saveAs(res.response, 'Dossier_' + new Date() + '.pdf')
}
req.setRequestHeader('Content-Type', 'application/json;charset=UTF-8');
req.send(JSON.stringify(params))
But ofc, there is more wider support if you use xhr + responseType = blob
The best thing you can do is just send content-disposition header and make a attachment - but then you can not use ajax... need to submit form (could be from iframe)
Another solution using $.ajax & FileSaver
I think the xhrFields should be the answer you look for...
$.ajax({
type: "POST",
url: "your-url/to/pdf/response",
data: params,
xhrFields: {
responseType: 'blob' // without this, you will get blank pdf!
},
}).done( function(res) {
blob = new Blob([res], { type: 'application/pdf' })
saveAs(blob, "response.pdf")
}).fail( function() {
alert("Error! Please try again later...");
});
This is the correct answer, without using the SaveAs function:
var req = new XMLHttpRequest();
req.open("POST", myUrl, true);
req.responseType = "blob";
req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
req.send(data);
req.onreadystatechange = function() {//Call a function when the state changes.
if(req.readyState == 4 && req.status == 200) {
console.log(req.responseText);
}
}
req.onload = function (event) {
var blob = req.response;
console.log(blob.size);
var link=document.createElement('a');
link.href=window.URL.createObjectURL(blob);
link.download="Dossier_" + new Date() + ".pdf";
link.click();
};
Ultimately it solved my problem. Thank you, Endless.

FormData parameters not pass to server with AJAX (pass fine with XMLHttpRequest)

I am trying to use ajax to pass a file (for upload it to server) and some other parameters to the server (perl cgi) but the server doesn't get the parameters.
The ajax:
$(function() {
$('#upload_file').click(function (){
var file = document.getElementById('file').files[0];
var formdata = new FormData();
formdata.append("Content-Type", "multipart/form-data");
formdata.append("sid", "1234");
formdata.append("file", file);
formdata.append("file_path_on_server", "/path/");
formdata.append("local_file_name", "sidebar_custom.css");
formdata.append("add_timestamp", "1"); // add timestamp to file name
$.ajax({
url : 'upload_file.cgi',
type : 'POST',
data : formdata,
processData: false, // tell jQuery not to process the data
contentType: false, // tell jQuery not to set contentType
success : function(data) {
console.log(data);
alert(data);
}
});
// var xhr = new XMLHttpRequest();
// xhr.open("POST","upload_file.cgi",true);
// if (xhr.status != 200) {
// alert("Error '" + xhr.status + "' occurred when trying to upload your file.");
// }
// xhr.send(formdata);
});
});
When I am using XMLHttpRequest instead (which commented out) all parameters pass to the server script as requested.
e.g.
I tried to print the parameter "sid" but it is empty with ajax and "1234" with XMLHttpRequest.
I don't want to use XMLHttpRequest because I can't receive respond from the server (e.g. some file name string).
Am I doing something wrong?

Ajax - Knowing if file download was correctly sent from server

I have an extjs ajax function that send a form to the server which returns a file to download with the correct Content-Disposition ="attachment; filename='test.zip'" header. The file can be downloaded with the normal file download window of the browser. However, the success callback function of the ajax request is not triggered and the ajax is pending indefinately waiting for a response.
Is there a way to tell the ajax function that the file was correctly sent from the server or not?
exportLayer = function(node_id){
Ext.Ajax.request({
method: "GET",
form: "exportForm",
url: "/basqui/layer/shapefile/export/" + node_id + "/",
success: function(r){
html = Ext.decode(r.responseText).html
Ext.get('pageContent').update(html);
},
});
}
Set binary configuration property of Ext.Ajax.request and in the response you would get
the binary data inside responseBytes property.
For example loading jpeg image:
Ext.Ajax.request({
url: "/path/to/image/test.jpg",
success: function(xhr) {
var b64encoded = btoa(String.fromCharCode.apply(null, xhr.responseBytes));
var img = Ext.create('Ext.Img', {
src: 'data:application/jpeg;base64,' + b64encoded
});
// add image somewhere
...
}
});

Categories

Resources