I'm upload an file using ajax,why the responseText from xmlhttprequest.responseText is returned empty?
My code:
req = new XMLHttpRequest();
req.file = file;
req.addEventListener('change', changeProgress);
req.onreadystatechange =
function() {
if(this.readyState == 4) {
//etc..
alert(req.responseText);
}
};
req.open('POST','/upload',true);
req.send(file);
Uploading files in XMLHttpRequest object is not supported for security reasons
EDIT: This is, however, possible with XMLHttpRequest 2
function upload(blobOrFile) {
var xhr = new XMLHttpRequest();
xhr.open('POST', '/server', true);
xhr.onload = function(e) { ... };
// Listen to the upload progress.
var progressBar = document.querySelector('progress');
xhr.upload.onprogress = function(e) {
if (e.lengthComputable) {
progressBar.value = (e.loaded / e.total) * 100;
progressBar.textContent = progressBar.value; // Fallback for unsupported browsers.
}
};
xhr.send(blobOrFile);
}
upload(new Blob(['hello world'], {type: 'text/plain'}));
Related
Basically I am using Ajax to call a C# WebMethod that returns a byte array that consists of an excel file. It is working in IE and Chrome but does not work in Firefox. The console is returning a readystate of 4 but a status of 0 in FireFox whereas in the other browsers it is getting into the if block where readystate is 4 and status is 200. Below is the code. If anyone knows what I am doing wrong, I would greatly appreciate the assistance but I have tried a bunch of steps to remedy the situation and none of them have been working.
If I put in an alert('got here') after the line containing xhttp.send, will it work in Firefox?
<script type="text/javascript">
$("#operation").click(function () {
var xhttp = new XMLHttpRequest();
xhttp.open("POST", "Default.aspx/GetText");
xhttp.addEventListener("progress", function (e) {
if (e.lengthComputable) {
//alert("TOTAL:" + e.total + " LOADED:" + e.loaded);
var percentComplete = Math.ceil((e.loaded / e.total) * 100);
progressBar.max = e.total;
progressBar.val(percentComplete);
//console.log(percentComplete);
}
}, false);
xhttp.responseType = 'blob';
xhttp.setRequestHeader("Content-Type", "application/json");
xhttp.onreadystatechange = function () {
var a;
//console.log(xhttp);
if (xhttp.readyState === 4 && xhttp.status === 200) {
var blob = xhttp.response;
var link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = "ItemMatrix.xlsx";
document.body.appendChild(link);
link.click();
} else {
console.log(xhttp);
}
};
xhttp.send(JSON.stringify({ sender: 'Generate Excel', itemLIST: $('#MainContent_itemnumberlist').val(), includeIMAGES: $('#<%= IncludeImages.ClientID %>').is(':checked') }));
});
</script>
I use XMLHttpRequest to send POST data to nodejs (expressjs api). The size of file about 200mb. When I do, Chrome crashes, but the Firefox doesn't. Does Chrome have a limited file size?
And how can I upload the large file via JavaScript?
This is my code send xhr request:
// create http request API AI Engine
var xhr = new XMLHttpRequest();
xhr.open('POST', url, true);
xhr.responseType = 'arraybuffer';
xhr.timeout = 3600000;
xhr.onload = function() {
// reponse measage
if (this.status === 200) {
var errorArea = document.getElementById('error-area');
errorArea.style.display = 'none';
zip.files = {};
// unzip File
zip.loadAsync(this.response)
.then(function(zip) {
// will be called, even if content is corrupted
for (const file in zip.files) {
if (zip.files.hasOwnProperty(file)) {
const fileObject = zip.files[file];
fileObject.async('arraybuffer').then(function(fileData) {
var fileSave = new Blob([new Uint8Array(
fileData)]);
// Save file
saveAs(fileSave, fileObject.name);
})
}
}
}, function(e) {
var errorArea = document.getElementById('error-area');
errorArea.style.display = 'block';
errorArea.innerHTML =
'<strong>Error</strong> Cant not unzip file return.';
});
// get response stream data
} else {
var errorArea = document.getElementById('error-area');
errorArea.style.display = 'block';
errorArea.innerHTML =
'<strong>Error</strong> Cant not analyze file: ' + this.statusText;
}
};
// Handle when have error with xhr, show message
xhr.onerror = function(err) {
var errorArea = document.getElementById('error-area');
errorArea.style.display = 'block';
errorArea.innerHTML =
'<strong>Error</strong> Cant not analyze file: ' + this.statusText;
};
// Handle when have timeout with xhr, show message
xhr.ontimeout = function() {
var errorArea = document.getElementById('error-area');
errorArea.style.display = 'block';
errorArea.innerHTML =
'<strong>Error</strong> Cant not analyze file: Request time out';
};
// Add custom header
xhr.setRequestHeader('Content-type', 'application/octet-stream');
xhr.setRequestHeader('file-name', Date.now().toString() + '.zip');
xhr.setRequestHeader('file-length', data.byteLength);
// Send arraybuffer to server
xhr.send(data);
});
I'm trying to convert the Blob data I receive to an array as follows:
var xhr = new XMLHttpRequest();
xhr.open('GET', "chrome://favicon/http://www.cnn.com/", true);
xhr.responseType = 'blob';
xhr.onload = function (e) {
if (this.status == 200) {
var favicon = new Uint8Array(this.response);
}
};
xhr.send();
But the line:
new Uint8Array(this.response);
doesn't result in an array. What's wrong here?
Figured it out:
var xhr = new XMLHttpRequest();
xhr.open('GET', "chrome://favicon/http://www.cnn.com/", true);
xhr.responseType = 'blob';
xhr.onload = function (e) {
if (this.status == 200) {
// get binary data as a response
//var blob = this.response;
//var favicon = new Uint8Array(this.response);
var reader = new FileReader();
reader.onload = function (e) {
mDataToTransmit.favicon = e.target.result;
transmitData();
};
reader.readAsDataURL(this.response);
}
};
xhr.send();
I am trying to make an XMLHttpRequest, however, I am having issues. The page keeps refreshing automatically even when returning false or using e.preventDefault(). I'm trying to get cities to eventually pass through an options block. (I've started the option section and will complete it after I figure out the get request issue.) I'm trying to do this using pure Javascript because I've already done it using Angular and Node. Any help would be appreciated.
HTML:
<form id="citySearchForm" method="get" onSubmit="return searchFormFunc();">
<div>
<p>Choose a city:</p>
<input type="text" placeholder="Enter a city" id="getCitiesInput" name="city">
<input type="submit" value="submit">
</div>
<div id="weather"></div
<p><span id="temp"></span></p
<p><span id="wind"></span></p>
</form>
Javascript:
var citySearch = document.getElementById("citySearchForm");
// citySearch.addEventListener("submit", searchFormFunc);
function searchFormFunc(e){
cityName = document.getElementById('getCitiesInput').value;
var searchCityLink = "http://autocomplete.wunderground.com/aq?query=";
var search = searchCityLink.concat(cityName);
console.log("link : " + search);
var xhr = XMLHttpRequest();
xhr.onreadystatechange = function() {
if(xhr.readyState == 4) {
var r = JSON.parse(xhr.response || xhr.responseText); // IE9 has no property response, so you have to use responseText
console.log(r);
} else {
console.log('error');
}
};
xhr.open("GET", link, true);
xhr.send(null);
var r = JSON.parse(xhr.response);
return false;
// e.preventDefault();
}
You are specifying that you want this to be an async request. So you need to parse your response inside of the onreadystatechange or onload.
function ajax(url, callback) {
var xhr;
if(typeof XMLHttpRequest !== 'undefined') xhr = new XMLHttpRequest();
else {
var versions = ["MSXML2.XmlHttp.5.0",
"MSXML2.XmlHttp.4.0",
"MSXML2.XmlHttp.3.0",
"MSXML2.XmlHttp.2.0",
"Microsoft.XmlHttp"]
for(var i = 0, len = versions.length; i < len; i++) {
try {
xhr = new ActiveXObject(versions[i]);
break;
}
catch(e){}
} // end for
}
/** Here you can specify what should be done **/
xhr.onreadystatechange = function() {
if(xhr.readyState < 4) {
return;
}
if(xhr.status !== 200) {
return;
}
// all is well
if(xhr.readyState === 4) {
callback(xhr);
}
}
xhr.open('GET', url, true);
xhr.send('');
}
Answer from documentation by user6123921
You have to use var xhr = new XMLHttpRequest();
you have to define an onreadystatechange event listener
xhr.onreadystatechange = function() {
if(xhr.readyState == 4) {
var r = JSON.parse(xhr.response || xhr.responseText); // IE9 has no property response, so you have to use responseText
console.log(r);
/* do stuff with response */
}
};
I have written the following code for download file from Google drive using JavaScript but I am not able to open file after completion of download its giving error like file format does not match my code as below,
function createPicker() {
var picker = new FilePicker({
apiKey: 'myapikey',
clientId: 'myclientID',
buttonEl: document.getElementById('ancggdgdgdd'),
onSelect: function (file) {
downloadFile(file);
}
});
}
and to read the content of file code as:
function downloadFile(doc) {
var myToken = gapi.auth.getToken();
var contentType = "text/plain;charset=utf-8";
var rawFile = new XMLHttpRequest();
rawFile.open("GET", doc.downloadUrl, false);
rawFile.setRequestHeader('Content-type', contentType)
rawFile.setRequestHeader('Authorization', 'Bearer ' + myToken.access_token);
rawFile.onreadystatechange = function () {
if (rawFile.readyState === 4) {
if (rawFile.status === 200 || rawFile.status == 0) {
sendFile(rawFile.responseText);//here I am sending httpcontext
}
}
}
//rawFile.responseType = "arraybuffer";
rawFile.send(null);
}
Try this function for downloading the files:
/**
* Download a file's content.
*
* #param {File} file Drive File instance.
* #param {Function} callback Function to call when the request is complete.
*/
function downloadFile(file, callback) {
if (file.downloadUrl) {
var accessToken = gapi.auth.getToken().access_token;
var xhr = new XMLHttpRequest();
xhr.open('GET', file.downloadUrl);
xhr.setRequestHeader('Authorization', 'Bearer ' + accessToken);
xhr.onload = function() {
callback(xhr.responseText);
};
xhr.onerror = function() {
callback(null);
};
xhr.send();
} else {
callback(null);
}
}
You can find more information in the following link: https://developers.google.com/drive/web/manage-downloads