Create object from URL - javascript

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/

Related

Getting Fetch/XMLHttpRequest API cannot load blob:url due to access control checks while making request from WKwebview

So, To download images/pdf that have blob: url in wkwebview, i injected javascript to my code.Here's the javaScript:
function(url) {
function blobToBase64String(blob, callback) {
var reader = new FileReader();
reader.onloadend = function() {
callback(this.result.split(",")[1]);
};
reader.readAsDataURL(blob);
}
if (url.startsWith("blob:")) {
var xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
xhr.responseType = "blob";
xhr.onload = function() {
if (this.status !== 200) {
return;
}
var blob = this.response;
blobToBase64String(blob, function(base64String) {
webkit.messageHandlers.downloadManager.postMessage({
url: url,
mimeType: blob.type,
size: blob.size,
base64String: base64String
});
});
};
xhr.send();
return;
}
var link = document.createElement("a");
link.href = url;
link.dispatchEvent(new MouseEvent("click"));}
This is the error i m getting:
XMLHttpRequest cannot load blob:https://url due to access control checks.
Is there any way to allow request in wkwebview. I m not sure, where to head forward! Is there any preferences in wkwebview, that needs to be enabled?

Use xhr.overrideMimeType but get server response first?

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

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();

xhr upload returns status 0 in firefox

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.

Categories