I have a function to download text file from server. It works on chrome but not work with IE 11.
Please help me.
Thanks and Regards.
// Get file name from url.
var filename = url.substring(url.lastIndexOf("/") + 1).split("?")[0];
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType = 'blob ';
xhr.onload = function () {
var a = document.createElement('a');
a.href = window.URL.createObjectURL(xhr.response); // xhr.response is a blob
a.download = filename; // Set the file name.
a.style.display = 'none';
document.body.appendChild(a);
a.click();
};
xhr.send();
xhr.onerror = function (e) {
alert("Error " + e.target.status + " occurred while receiving the document.");
};
Related
I have a LotusScript agent that has the following code at the end
Set nam = session.Createname(respParty)
Print "Content-type: text/plain"
Print nam.Abbreviated
I have a JavaScript button that contains the following prior to a submit()
var noEmployees = document.getElementById('NoEmployees').value;
var stateName = document.getElementById('State').value;
var url = 'http://' + window.location.host + '/ebsprospects.nsf/GetResponsiblePerson?OpenAgent&NoEmployees=' + noEmployees + '&State=' + stateName;
var xhttp = new XMLHttpRequest();
xhttp.open("GET", url);
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
}
};
alert (xhttp.responseText);
document.getElementById("ResponsibleParty").innerHTML = xhttp.responseText;
Everything is working except it is getting back a blank value.
If I put the URL:
http://[webaddress]/[dbname].nsf/GetResponsiblePerson?OpenAgent&NoEmployees=20&State=IL
into the browser exactly as I am passing it into the JS code it returns:
X Content-type: text/plain Susanne Anderson/CBS
What am I doing wrong?
Is my JS code in the wrong order?
var noEmployees = document.getElementById('NoEmployees').value;
var stateName = document.getElementById('State').value;
var url = 'http://' + window.location.host + '/ebsprospects.nsf/GetResponsiblePerson?OpenAgent&NoEmployees=' + noEmployees + '&State=' + stateName;
var xhttp = new XMLHttpRequest();
xhttp.open("GET", url);
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
alert (xhttp.responseText);
document.getElementById("ResponsibleParty").innerHTML = xhttp.responseText;
}
};
xhttp.send();
Hope this will help.
I am trying to download the file saved in s3. So I have codes like below.
static public function download($key, $disk = 's3') : object
{
$file = FileHelper::get($key);
$local = Storage::disk('local');
$local->put(basename($key), $file);
$pathToFile = storage_path().'/app/'.basename($key);
$headers = [
'Content-Type' => \GuzzleHttp\Psr7\mimetype_from_filename(basename($key)),
'Content-Description' => 'File Transfer',
'Content-Disposition' => "attachment; filename=' ". basename($key),
'filename'=> basename($key)
];
$repsonse = response()->download($pathToFile, basename($key), $headers)->deleteFileAfterSend(true);
ob_end_clean();
return $repsonse;
}
And I have the javascript code like below.
downloadFile() {
var app = this;
var url = baseRoute + 'files/' + this.fileId + '/download';
axios.get(url, {
headers: {
Authorization: 'bearer ' + this.Authentication.tokenData().token,
responseType : "blob"
}
}).then(function (response) {
var today = ((new Date()).toISOString()).slice(2,10),
filename = today.replace(/-/gi, "")+' '+ app.fileTitle;
let blob = new Blob([response.data], {
type: response.headers['content-type']
});
let link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = filename;
link.click();
}).catch(function (response) {
console.log(response);
});
}
The file is downloaded, however, the file is corrupted. (it would not open) I checked S3 bucket to see if the file is corrupted during upload, but it was fine there.
What am I doing wrong? Any advice or suggestion would be appreciated.
Thank you in advance.
Added: when I tried to view the image, it returned white squared which means its base64 encoded image. Does it have to do with being empty file?
I had to use standard XMLHttpRequest to work it like below.
downloadFile() {
var app = this;
var url = baseRoute + 'files/' + this.fileId + '/download';
var xhr = new XMLHttpRequest();
xhr.open("POST", url);
xhr.setRequestHeader('Authorization', 'bearer ' + this.Authentication.tokenData().token);
xhr.responseType = "arraybuffer";
xhr.onload = function () {
if (this.status === 200) {
var today = ((new Date()).toISOString()).slice(2,10),
filename = today.replace(/-/gi, "")+' '+ app.fileTitle;
var blob = new Blob([xhr.response], {type: xhr.getResponseHeader('content-type')});
var objectUrl = URL.createObjectURL(blob);
let link = document.createElement('a');
link.href = objectUrl;
link.download = filename;
link.click();
window.URL.revokeObjectURL(blob);
}
};
xhr.send();
},
I am trying to crawl a web page using javascript by making use of api on the click of download button. But I don't receive any responseText in this and same api works using curl.
download.addEventListener('click',function(){
document.getElementById('check').innerHTML = url;
var yql = 'http://query.yahooapis.com/v1/public/yql?q=' + encodeURIComponent('select * from html where url="' + url + '"') + '&format=json&callback=?';
document.getElementById('check').innerHTML = yql;
var request = new XMLHttpRequest();
request.onreadystatechange = function(){
document.getElementById('check').innerHTML= request.readyState;
if(request.readyState ===XMLHttpRequest.DONE) {
document.getElementById('check').innerHTML= request.responseText;
}
};
request.open("GET", yql, true);
request.send;
},false);
Just remove the callback from the ypl and then this code works fine :
download.addEventListener('click',function(){
document.getElementById('check').innerHTML = url;
var yql = 'http://query.yahooapis.com/v1/public/yql?q=' + encodeURIComponent('select * from html where url="' + url + '"') + '&format=jsonp';
document.getElementById('check').innerHTML = yql;
var request = new XMLHttpRequest();
request.open("GET", yql, true);
request.send();
request.onreadystatechange = function(){
document.getElementById('check').innerHTML= request.readyState + request.status;
if(request.readyState ===4) {
document.getElementById('check').innerHTML= request.responseText;
}
};
},false);
I am trying to export data to file.
The export works great for pretty much all files, but when I try to export large datasets it is not working.
any clues?
here is the code
a.href = 'data:' + mimeType + ',' + encodeURIComponent(content);
a.setAttribute('download', fileName);
document.body.appendChild(a);
a.click();
I used the following function. Not sure why it solved the problem. I guess it is a browser thing.
download(content, fileName, mimeType) {
var a = document.createElement('a');
mimeType = mimeType || 'application/octet-stream';
if (navigator.msSaveBlob) { // IE10
return navigator.msSaveBlob(new Blob([content], { type: mimeType }), fileName);
} else if ('download' in a) { //html5 A[download]
var csvData = new Blob([content], { type: mimeType });
var csvUrl = URL.createObjectURL(csvData);
//a.href = 'data:' + mimeType + ',' + encodeURIComponent(content);
a.href = csvUrl;
a.setAttribute('download', fileName);
document.body.appendChild(a);
a.click();
console.log(a);
//document.body.removeChild(a);
/*
setTimeout(function() {
a.click();
console.log(a);
document.body.removeChild(a);
}, 66);*/
return true;
} else { //do iframe dataURL download (old ch+FF):
var f = document.createElement('iframe');
document.body.appendChild(f);
f.src = 'data:' + mimeType + ',' + encodeURIComponent(content);
setTimeout(function() {
document.body.removeChild(f);
}, 333);
return true;
}
},
I'm trying to upload an image via POST with javascript to a site that I can't modify the source of.
The page has a form that allows you to upload images:
<form enctype="multipart/form-data" action="/u.php" method="post">
<input name="file" type="file"> <input type="submit" value="Upload File">
</form>
I want to be able to upload images with javascript but I can't get anything to work, I'm not sure if this is even possible...
My JS so far:
file = document.getElementById('fileinput').files[0];
r = new FileReader();
r.onloadend = doUpload;
r.readAsBinaryString(file)
function doUpload(el){
file = el.target.result;
XMLHttpRequest.prototype.sendAsBinary = function(string) {
var bytes = Array.prototype.map.call(string, function(c) {
return c.charCodeAt(0) & 0xff;
});
this.send(new Uint8Array(bytes).buffer);
};
var xhr = new XMLHttpRequest();
xhr.open('POST', 'http://upload.domain.com/u.php', true);
var boundary = 'ohaiimaboundary';
xhr.setRequestHeader(
'Content-Type', 'multipart/form-data; boundary=' + boundary);
xhr.sendAsBinary([
'--' + boundary,
'Content-Disposition: form-data; name="file"; filename="test.jpg"',
'Content-Type: multipart/form-data',
'',
file,
'--' + boundary + '--'
].join('\r\n'));
}
Thanks
EDIT:
figured this one out, kind of, this should work with a little modification (png is hardcoded in)
function doUpload(fl){
var file = fl.target.result;
XMLHttpRequest.prototype.sendAsBinary = function(datastr) {
var bb = new BlobBuilder();
var data = new ArrayBuffer(1);
var ui8a = new Uint8Array(data, 0);
for (var i in datastr) {
if (datastr.hasOwnProperty(i)) {
var chr = datastr[i];
var charcode = chr.charCodeAt(0)
var lowbyte = (charcode & 0xff)
ui8a[0] = lowbyte;
bb.append(data);
}
}
var blob = bb.getBlob();
this.send(blob);
}
var xh = new XMLHttpRequest();
xh.open('post', 'http://upload.domain.com/u.php', true);
xh.onreadystatechange = function(){
if(this.readyState != 4){
return;
}
else{
console.log(this.responseText);
}
};
var boundary = '--fgsfds--';
xh.setRequestHeader('Content-Type', 'multipart/form-data; boundary=' + boundary);
xh.sendAsBinary([
'--' + boundary,
'Content-Type: image/png',
'Content-Disposition: form-data; name="file"; filename="testz.png"',
'',
file,
'--' + boundary + '--',
''].join('\n'));
}
function mkUpload(){
var r = new FileReader();
r.onloadend = doUpload;
r.readAsBinaryString(document.upload.file.files[0]);
}
test PHP:
<?
echo sprintf('<pre>%s</pre>', print_r($_FILES, true));
?>
Actually, have you tried xhr.send(FormData)? FormData allows you to
append File objects, which will be treated as binary content and using
it with XHR sends a multipart/form-data. There's no need to construct it yourself.
var formData = new FormData();
var file = document.querySelector('input[type="file"]').files[0];
if (file) {
formData.append("file", file);
}
var xhr = new XMLHttpRequest();
xhr.open('POST', '/u.php', true);
xhr.onload = function(e) { ... };
xhr.send(formData);