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
}
}
};
}
Related
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
I have this event handler that does downloading and that's working great on all browsers except IE, so I handled it with msSaveBlob and it download file, but when I open it, it said format isn't good, so my guess is that I don't use valid data in blob.
$(document).on('click', '.register-file-uploader-download-file', function () {
let $fileResultsItem = $(this).closest('.form-fields__file-results-item');
const fileName = $fileResultsItem.find('.multiple-files-upload-item').data('filename');
const fileUrl = $fileResultsItem.find('.multiple-files-upload-item').val();
if (fileUrl.length > 0) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (this.readyState === 4 && this.status === 200) {
var url = window.URL || window.webkitURL;
let blobFileUrl = url.createObjectURL(this.response);
if (window.navigator && navigator.msSaveBlob) { // For IE
const blobObj = new Blob([this.response], { type: 'application/octet-stream' });
return navigator.msSaveBlob(blobObj, fileName);
}
const a = document.createElement('a');
a.style.display = 'none';
a.href = blobFileUrl;
a.download = `${fileName}`;
document.body.appendChild(a);
a.click();
url.revokeObjectURL(blobFileUrl);
}
};
xhr.open('GET', fileUrl);
xhr.responseType = 'blob';
xhr.send();
}
});
I found error. Code is working fine, problem is in fact that I tried to download image that was uploaded on stage server, and when I uploaded and downloaded it and it's working
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();
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);
}
});
}
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?