Download in File CodeIgniter FTP class Ajax - javascript

I am using the FTP class in CodeIgniter, they have a function for downloading the file from the FTP.
I would like to save a file from the server to my computer. it saves my file to my download folder but the file "Can not open the file".
When i use other method ca does not save the file.
Code PHP
$source_to_server = $this->input->post('path');
$file = $this->input->post('file');
header("Cache-Control: ");
header("Content-type: text/plain");
header("Content-Disposition: attachment; filename=".$file);
$row = $this->model_front->get_website($id_ftp_websites)->row();
$config['hostname'] = $row->host_ftp;
$config['username'] = $row->login_ftp;
$config['password'] = $row->password_ftp;
$this->ftp->connect($config);
$this->ftp->download($source_to_server, 'php://output', 'auto');
main.js (Ajax)
var path = $("#path").text()+folderselect_contextmenu.find(".name").text();
var file = folderselect_contextmenu.find(".name").text();
$.ajax({
type: "POST",
url: $(this).attr('href'),
data: {'path':path,'file':file},
success: function(response, status, xhr) {
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: type });
if (typeof window.navigator.msSaveBlob !== 'undefined') {
window.navigator.msSaveBlob(blob, filename);
} else {
var URL = window.URL || window.webkitURL;
var downloadUrl = URL.createObjectURL(blob);
if (filename) {
var a = document.createElement("a");
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
}
}
});
e.preventDefault();

Related

Generate Zip file contain list of Files without JSZip library

Hello Developers,
I'm trying to download the list of files getting form XMLHttpRequest() request method and store it in the array of files. I wanted to zip all the files in an array using javascript without using any 3rd party library.
I have tried to achieve this by URL.createObjectURL(url) and URL.revokeObjectURL(url) method but the file I'm getting is corrupted.
I'm Sharing my code snippet please help me out
const URLS = [
'https://vr.josh.earth/assets/2dimages/saturnv.jpg',
'https://vr.josh.earth/assets/360images/hotel_small.jpg',
'https://vr.josh.earth/assets/360images/redwoods.jpg'
];
$(document).ready(function () {
debugger
$("#downloadAll").click(function () {
var blob = new Array();
var files = new Array();
URLS.forEach(function (url, i) {
getRawData(url, function (err, data) {
debugger
var mydata = data;
// mydata = btoa(encodeURIComponent(data));
// var blobData = b64toBlob(mydata , 'image/jpg');
var blobData = new Blob([mydata], { type: 'image/jpg' });
blob.push(blobData);
var filename = "testFiles" + i + ".jpg";
var file = blobToFile(blobData, filename);
files.push(file);
debugger
if (files.length == URLS.length) {
// saveData(blob, "fileName.zip");
var AllBlobData = new Blob([blob], { type: 'application/zip' });
saveData(AllBlobData, "Test.zip");
// saveFile("DownloadFiles.zip", "application/zip", files)
}
});
});
});
});
//Retriving record using XMLHttpRequest() method.
function getRawData(urlPath, callback, progress) {
var request = new XMLHttpRequest();
request.open("GET", urlPath, true);
request.setRequestHeader('Accept', '');
if ('responseType' in request)
request.responseType = "arraybuffer"
if (request.overrideMimeType)
request.overrideMimeType('text/plain; charset=x-user-defined');
request.send();
var file, err;
request.onreadystatechange = function () {
if (this.readyState === 4) {
request.onreadystatechange = null;
if (this.status === 200) {
try {
debugger
var file = request.response || request.responseText;
} catch (error) {
throw error;
}
callback(err, file);
} else {
debugger
callback(new Error("Ajax Error!!"))
}
} else {
debugger
}
}
}
//For Saving the file into zip
var saveData = (function () {
var a = document.createElement("a");
document.body.appendChild(a);
a.style = "display: none";
return function (data, fileName) {
// var AllBlobs = new Blob([data], { type: "" });//application/zip //octet/stream
// var url = window.URL.createObjectURL(AllBlobs);
var url = window.URL.createObjectURL(data);
a.href = url;
a.download = fileName;
a.click();
window.URL.revokeObjectURL(url);
};
}());
//Downloaded Zip File
enter image description here

How to receive binary file as response and render file using javascript?

enter image description hereWe have a service that interacts with box.com and returns a file in binary format.
I am trying to hit that service from java-script to get binary file and render/dowload as actual file using below code but no response is being received (I have verified that service is returning the response).
Console logs are blank.
Any help is greatly appreciated.
<h1>File Download</h1>
<button type="button" onclick="loadDoc()">Download</button>
<p id="demo"></p>
function loadDoc() {
var xhr = new XMLHttpRequest();
xhr.open('POST', URL, true);
xhr.setRequestHeader("Content-type", "application/json");
xhr.setRequestHeader("Authorization", "Basic xxcxcsdfdfdferererer=");
//xhr.setRequestHeader("Access-Control-Allow-Origin", true);
xhr.responseType = 'arraybuffer';
xhr.send(JSON.stringify({projects: [{id: "xxxxxx", fileId: "1234456566"}]}));
xhr.onreadystatechange = function () {
if (this.readyState == 4 && this.status === 200) {
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 = typeof File === 'function' ? new File([this.response], filename, { type: type }) : new Blob([this.response], { type: type });
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
}
}
};
}

submitting full HTML page to x-www-form-urlencoded as querystring encoding

I am trying to submit full HTML Page to server but I dont have a form to submit. I am not sure if i am doing it correctly but using javascript I am trying to rebuild a json object {html: htmlPage, fileName: "foo" } into a query string and then submit it to server here is the code I have. when i console str the HTML page doesnt look right. I am using jquery
var htmlPage = $("html").html();
var str = { html: htmlPage, fileName: "foo" };
var params = jQuery.param( str );
var xhr = new XMLHttpRequest();
xhr.open('POST', '/', true);
xhr.responseType = 'arraybuffer';
xhr.onload = function () {
if (this.status === 200) {
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([this.response], { type: type });
if (typeof window.navigator.msSaveBlob !== 'undefined') {
window.navigator.msSaveBlob(blob, filename);
} else {
var URL = window.URL || window.webkitURL;
var downloadUrl = URL.createObjectURL(blob);
if (filename) {
var a = document.createElement("a");
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
}
}
};
xhr.onerror = function(e) {
console.log('in error', e);
};
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded;charset=UTF-8');
xhr.send(params);
if you have jQuery, then just use ajax http://api.jquery.com/jquery.ajax/.
This will base64 encode your html, then on the server side you only have to base64 decode it, then use it. And hey the entire html code can't be counted as form-data, it's "text/html".
(updated) Try it, let me know.
// javascript
function _upload(html_string)
{
return $.ajax({
url: '/',
type: 'POST',
headers: {"Content-Type": "application/x-www-form-urlencoded"},
data: {html: btoa(html_string), fileName: "foo" },
success: function(data, textStatus, req){
console.log(textStatus);
},
error: function(req , textStatus, errorThrown){
console.log("jqXHR["+textStatus+"]: "+errorThrown);
console.log('jqXHR.data', req.responseText);
}
});
}

File download from google

I'm working on Google drive integration with salesforce. Currently I'm facing file corruption when I tried to download file using java script. My code is as followed
function downloadGDriveFile() {
var id = '0B3EI0BFOUwSydHZNZXdIZ3lDZzg';
var downloadUrl = 'https://www.googleapis.com/drive/v2/files/'+ id+'?alt=media';
var accessToken = MY ACCESS TOKEN;
var mType = 'image/jpeg';
var name = 'Internet_of_Things.jpg';
if (downloadUrl) {
var xhr = new XMLHttpRequest();
xhr.open('GET', downloadUrl);
xhr.setRequestHeader('Authorization', 'Bearer ' + accessToken);
xhr.onload = function() {
onDownload(xhr.response);
};
xhr.onerror = function() {
//downloadFile(null);
};
xhr.send();
}
else {
alert("Unable to download file.");
}
}
function onDownload(data) {
var filename = 'Internet_of_Things.jpg';
var blob = new Blob([data], { type: "image/jpeg" });
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;
}
alert(11);
//URL.revokeObjectURL(downloadUrl);
setTimeout(function () { URL.revokeObjectURL(downloadUrl); }, 1); // cleanup
}
}
when file is downloaded file is corrupted.File content shown as follow
���� JFIF �� hExif MM * > F( 1 N Paint.NET v3.5.11 �� C �� C�� ��" ��
Dose any one can help me to sort this out. Do I need to encode or decode the Response from Google REST API?

How to download an Excel File via Ajax technologie

I have some problems to handle an excel file download with Ajax. I Have found this source code on an another webpage I copied that in my webproject:
$.ajax({
type: "POST",
url: "myStrutsAction.action",
data: {p1:p1, p2:p2},
success: function(response, status, xhr){
disableMyLoadingUserPopupScreen();
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, '');
disposition);
}
var type = xhr.getResponseHeader('Content-Type');
var blob = new Blob([response], { type: type });
if (typeof window.navigator.msSaveBlob !== 'undefined') {
window.navigator.msSaveBlob(blob, filename);
} else {
var URL = window.URL || window.webkitURL;
var downloadUrl = URL.createObjectURL(blob);
if (filename) {
var a = document.createElement("a");
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);
}
}
});
This kind of code shows the user dialog for saving or opening the specific excelfile. But if I have tried to open the Excelfile, the File are damaged and couldn´t be opened (I have viewed in Notepad++ editor, but here I see some cryptical characters):
Here is my Struts2 execute method on the server:
public String execute(){
// Create Excel File
returnFileAsStream("myExcelfile");
return null;
}
In this method I have written the HTTP Response Header:
private void returnFileAsStream(final String filename) throws IOException {
final InputStream is = new FileInputStream(filename);
OutputStream os = null;
try {
response.setContentType("application/octet-stream");
response.setHeader("Cache-Control", "maxage=3600");
response.setHeader("Pragma", "public");
response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
os = response.getOutputStream();
int length;
byte buf[] = new byte[1024];
while ((length = is.read(buf)) > 0) {
os.write(buf, 0, length);
}
is.close();
os.close();
} finally {
// other code, not important
}
}
It is correct, that it is not possible to handle a file download with Ajax? I´m of the opinion, that it is the problem, that I want to handle some steps with binary data instead of text data and Ajax couldn´t be handle some steps with binary code?
Set the content-type to :
For BIFF .xls files
application/vnd.ms-excel
For Excel2007 and above .xlsx files
application/vnd.openxmlformats-officedocument.spreadsheetml.sheet

Categories