xhr upload returns status 0 in firefox - javascript

The code below is working in IE and Chrome but not in any version of firefox that I try. In firefox I get a status of 0 in the xhr.onload function instead of a status of 200.
Also in firefox for a response I am getting Blob { size: 9728, type: "application/xml" } but in chrome I am getting Blob {type: "text/plain", size: 9728, slice: function}
function fileUpload(idx){
var xhr = new XMLHttpRequest();
xhr.open('GET', upload_q[q_index_get(idx)], true);
xhr.responseType = 'blob';
var uid = Math.random().toString(34).substr(2);
xhr.onload = function(e) {
console.log('---- this.status ----');
console.log(this.status);
if (this.status == 200) {
var myBlob = this.response;
// myBlob is now the blob that the object URL pointed to.
console.log(myBlob);
var oMyForm = new FormData();
oMyForm.append("uid", uid );
oMyForm.append("fname", upload_fname_q[q_index_get(idx)]);
oMyForm.append("fsize", myBlob.size)
oMyForm.append("q_key", idx)
oMyForm.append("myFile", myBlob);
var oReq = new XMLHttpRequest();
oReq.open("POST", "/client/upload");
oReq.send(oMyForm);
}
};
xhr.send();
return uid;
}

I stopped checking if status == 200 and the upload works. The strange thing is that I created that code based on what I read on MDN.

Related

How to pass base64encode string through XMLHttpRequest() post request

I am trying to upload a image to server,In that i have converted image to base64encode string and i need to pass that base64encode string to webservice,that webservice convert the base64 string to file and saving in database.but base64encode string has huge length approximately(85,000) when i pass this string to webservice i am getting the following error.
Failed to load resource: the server responded with a status of 400 (Bad Request)
i need to pass this by using only XMLHttpRequest() with out using the ajax,jquery please help me.
below is my code.
var filesToBeUploaded = document.getElementById("afile");
var file = filesToBeUploaded.files[0];
var reader = new FileReader();
reader.onload = function(event) {
var binaryStringResult = reader.result;
var binaryString =binaryStringResult.split(',')[1];
var xhr = new XMLHttpRequest();
xhr.open("POST","http://url/api/jsonws/Global-portlet.org_roles/add-file-entry?repositoryId=11304&folderId=0&sourceFileName=test108.jpeg&mimeType=image%2Fjpeg&title=test108.jpeg&description=test108.jpeg&changeLog=test108.jpeg&basecode64="+ binaryString);
xhr.setRequestHeader("Authorization","BasicbmFyYXlhbmFAdmlkeWF5dWcuY29tOnRlc3Q=");
xhr.setRequestHeader('Content-type','application/x-www-form-urlencoded');
xhr.send();
xhr.onload = function() {
alert('in sucess');
};
xhr.onerror = function(e) {
alert('in error');
};
}
reader.readAsDataURL(file);
For POST, don't include it in the URL, you need to put it in the body, i.e.
xhr.send(binaryString);
I doubt your Content-Type of application/x-www-form-urlencoded is correct in this case.
I think the issue that you encountering here is that you are exceeding the maximum length of a query string.
What you need to do is something like the following:
var xhr = new XMLHttpRequest();
var url = "http://url/api/jsonws/Global-portlet.org_roles/add-file-entry";
var params = "repositoryId=11304&folderId=0&sourceFileName=test108.jpeg&mimeType=image%2Fjpeg&title=test108.jpeg&description=test108.jpeg&changeLog=test108.jpeg&basecode64="+ binaryString;
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.setRequestHeader("Content-length", params.length);
xhr.setRequestHeader("Connection", "close");
xhr.onreadystatechange = function() {
if(xhr.readyState == 4 && xhr.status == 200) {
alert(xhr.responseText);
}
}
xhr.send(params);
Hope that helps

convert URL into file object using javascript only

Link given:
example.com/data/videos/videoname.mp4
How to pass this link as fileInput?
var fileUrl = window.URL.createObjectURL(fileInput);
All should be done in javascript only.
Need a solution in pure javascript only not using any jquery.
You can use ajax and get blob
var url = 'http://example.com/data/videos/videoname.mp4';
var xhr = new XMLHttpRequest();
xhr.open('GET', 'blob:'+url, true);
xhr.responseType = 'blob';
xhr.onload = function(e) {
if (this.status == 200) {
var myObject = this.response;
}
};
xhr.send();

XMLHttpRequest returns wrongly encoded characters

I use XMLHttpRequest to read the PDF document
http://www.virtualmechanics.com/support/tutorials-spinner/Simple2.pdf
%PDF-1.3
%âãÏÓ
[...]
and print its content out to console:
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
console.log(xhr.responseText);
console.log('âãÏÓ');
}
};
xhr.open('GET', 'http://www.virtualmechanics.com/support/tutorials-spinner/Simple2.pdf', true);
xhr.send();
However, the console says
%PDF-1.3
%����
[...]
âãÏÓ
(The last line is from the reference console.log above to verify that the console can actually display those characters.)
Apparently, the characters are wrongly encoded at some point. What's going wrong and how to fix this?
XMLHttpRequest's default response type is text, but here one is actually dealing with binary data. Eric Bidelman describes how to work with it.
The solution to the problem is to read the data as a Blob, then to extract the data from the blob and plug it into hash.update(..., 'binary'):
var xhr = new XMLHttpRequest();
xhr.open('GET', details.url, true);
xhr.responseType = 'blob';
xhr.onload = function() {
if (this.status === 200) {
var a = new FileReader();
a.readAsBinaryString(this.response);
a.onloadend = function() {
var hash = crypto.createHash('sha1');
hash.update(a.result, 'binary');
console.log(hash.digest('hex'));
};
}
};
xhr.send(null);
The MIME type of your file might not be UTF-8. Try overriding it as suggested here and depicted below:
xhr.open('GET', 'http://www.virtualmechanics.com/support/tutorials-spinner/Simple2.pdf', true);
xhr.overrideMimeType('text/xml; charset=iso-8859-1');
xhr.send();

Safari interprets Objects from xhr request as String not as Objects

i am trying to load a json file with objects via xhr request.
var xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
xhr.responseType = "jsonp";
xhr.onload = function (data) {
discog = xhr.response;
};
xhr.send();
this works fine in chrome, safari however interprets the response as a string - what am I doing wrong here?
thank you very much
One problem is that "jsonp" is not a valid responseType.
Try this instead:
var xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
xhr.onload = function(){
discog = JSON.parse(xhr.responseText);
};
xhr.send();
Or this:
var xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
xhr.responseType = "json";
xhr.onload = function(){
discog = xhr.response;
};
xhr.send();

Create object from URL

Is there a way to create an object / blob object from URL like this:
blob:http://127.0.0.1:8888/4bd9114b-1adb-40ce-b55b-a38f803b849a
and like this: blob:111d6876-dc9c-4ec5-84a1-1004cae101b4
Here is the code I've tried so far:
var xhr = new XMLHttpRequest();
xhr.open('GET', source, true);
xhr.responseType = 'blob';
xhr.onload = function(e) {
alert('Response status - ' + this.status);
if (this.status == 200) {
var myBlob = this.response;
alert("Converted to Blob");
}
};
xhr.send();
But the response is always this.status is 0
Update:
The blob came from the clipboard
This is a start, it should answer for the first url you specified.
See https://developer.mozilla.org/en-US/docs/Web/API/Blob
and
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Typed_arrays
var blobPart=["http%3A//127.0.0.1%3A8888/4bd9114b-1adb-40ce-b55b-a38f803b849a"];
var blob = new Blob(blobPart, {type: "application/octet-binary"}); // pass a useful mime type here
console.log("blob ~ ", blob);
var urlObj = URL.createObjectURL(blob);
console.log("url ~", urlObj);
//using FileReader to read Blob
var reader = new FileReader();
reader.addEventListener("loadend", function() {
console.log("reader result ~ ",reader.result);
});
reader.readAsDataURL(blob);
See console: http://jsfiddle.net/Seandeburca/P9HRa/

Categories