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
Related
I am trying to POST to a google maps service. If you click on the URL you will see the JSON response that I am expecting to get
var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
var xhr = new XMLHttpRequest()
var url = "https://maps.googleapis.com/maps/api/directions/json?origin=Exeter&destination=Deal®ion=uk&mode=driving"
xhr.open('POST', url, true)
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.onload = function() {
// do something to response
alert(this.responseText)
}
However, this code gets stops after xhr.onload = function(). So I never get the response back. Is there an error in my code?
You forgot to send the request.
xhr.send("The string of application/x-www-form-urlencoded data you are POSTING goes here");
var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
var xhr = new XMLHttpRequest()
var url = "https://maps.googleapis.com/maps/api/directions/json?origin=Exeter&destination=Deal®ion=uk&mode=driving"
xhr.open('POST', url, true)
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.onload = function() {
// do something to response
alert(this.responseText)
}
xhr.send("data to be send");
Try this.
I want to get a Base64 encoded file from the server in order to use it in a dataURL so I use:
xhr.overrideMimeType("text/plain; charset=x-user-defined");
So I get the unprocessed data to perform the base64 encoding on.
But I also want to get the mimetype originally returned from the server to declare my dataURL:
var dataUrl = 'data:'+mimetype+';base64,'+b64;
when I try something like the following:
var xhr = new XMLHttpRequest();
xhr.open("GET", url, false);
var mimetype = xhr.getResponseHeader('content-type');
xhr.overrideMimeType("text/plain; charset=x-user-defined");
xhr.send(null);
the content-type returned is always null
Full source:
function getFileDataUrl(link,mimetype)
{
var url = location.origin+link;
var getBinary = function (url)
{
var xhr = new XMLHttpRequest();
xhr.open("GET", url, false);
if(mimetype == null)
{
mimetype = xhr.getResponseHeader('content-type');
console.log('mimetype='+mimetype);
}
xhr.overrideMimeType("text/plain; charset=x-user-defined");
xhr.send(null);
return xhr.responseText;
};
var bin = getBinary(url);
var b64 = base64Encode(bin);
var dataUrl = 'data:'+mimetype+';base64,'+b64;
return dataUrl;
}
var dataUrl = getFileDataUrl(link,null);
You can set responseType of XMLHttpRequest to "blob" or "arraybuffer" then use FileReader, FileReader.prototype.readAsDataURL() on response. Though note, onload event of FileReader returns results asynchronously. To read file synchronously you can use Worker and FileReaderSync()
var reader = new FileReader();
reader.onload = function() {
// do stuff with `reader.result`
console.log(reader.result);
}
var xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
xhr.responseType = "blob";
xhr.onload = function() {
reader.readAsDataURL(xhr.response);
}
xhr.send(null);
At chromium synchronous XMLHttpRequest() is deprecated, see https://xhr.spec.whatwg.org/.
You can use Promise at main thread to get data URI of requested resource using either Worker or when FileReader load event is dispatched. Or use synchronous XMLHttpRequest() and FileReaderSync() at Worker thread, then listen for message event at main thread, use .then() to get Promise value.
Main thread
var worker = new Worker("worker.js");
var url = "path/to/resource";
function getFileDataUrl(url) {
return new Promise(function(resolve, reject) {
worker.addEventListener("message", function(e) {
resolve(e.data)
});
worker.postMessage(url);
})
}
getFileDataUrl(url)
.then(function(data) {
console.log(data)
}, function(err) {
console.log(err)
});
worker.js
var reader = new FileReaderSync();
var request = new XMLHttpRequest();
self.addEventListener("message", function(e) {
var reader = new FileReaderSync();
request.open("GET", e.data, false);
request.responseType = "blob";
request.send(null);
self.postMessage(reader.readAsDataURL(request.response));
});
plnkr http://plnkr.co/edit/gayWpkTVydmKYMnPr3jD?p=preview
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();
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();
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/