Angular JS with PDFTron - javascript

I am trying to get a blob as a URL but i get an error on this line :
xhr.send()
The error message is angular.js:13920 Error: Failed to execute 'send' on 'XMLHttpRequest': The object's state must be OPENED.
But in the code I am using xhr.open('GET', blobValue) as shown in my code here
if(someBlobValue){
var viewerElement = $document[0].getElementById('viewer');
var myWebViewer = new PDFTron.WebViewer({
path: 'lib',
pdftronServer: 'https://demo.pdftron.com' // remove
}, viewerElement);
var xhr = new XMLHttpRequest;
xhr.responseType = 'blob';
xhr.onload = function() {
var recoveredBlob = xhr.response;
var reader = new FileReader;
reader.readAsDataURL(recoveredBlob);
};
xhr.open('GET', someBlobValue);
xhr.setRequestHeader('Content-type', 'application/pdf');
xhr.send(); //error here although its open?
//var file = new File([newValue], 'somefile.pdf');
myWebViewer.loadDocument(xhr.response, { filename: 'somefile.pdf'});
Currently i have the document as a blob but i am trying to load it to pdftron library and unfortunately i dont seem to find the myWebViewer.getInstance().loadLocalFile method in the DOM (its undefined).
Would appreciate any pointers as its the first time trying to use pdftron in the angularjs app.
NOTE : This is inside a directive.

You need to wait for the DOM element containing WebViewer to trigger the ready event, for the ReaderControl instance, returned from getInstance(), to be defined.
For example:
$(viewerElement).on('ready', function() {
myWebViewer.getInstance().loadLocalFile(someBlobValue);
});

There is nothing wrong in your code logically,
You just forgot to instantiate the XHR object over here var xhr = new XMLHttpRequest;.
You can correct it by doing this var xhr = new XMLHttpRequest();

Related

javascript createObjectURL corrupt file

im using the following javascript to create an object url, the only problem is when loading the url blob:http:///mysite.com/randomhash the file is corrupt.
var audioFile = null;
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
audioFile = new Blob([xhttp.response], {type: 'audio/mp3'});
}
};
xhttp.open("GET", "myMp3File.mp3", false);
xhttp.send();
var file = new File([audioFile], "myMp3File.mp3", {type: "audio/mp3", lastModified: Date.now()});
any ideas as to why this would create a blob url with a corrupt mp3 ?
Multiple problems here.
First, you are dealing with asynchronous code. You will need to use a callback in order to use the response of your XHR request.
Then, even if you did so, there are good chances that it will still not work.
This is because the response you get is plain text UTF16 and that some bytes will get mangled by encoding.
The real solution in your case is to directly request the response as a Blob.
You can do so with the XMLHttpRequest.responseType parameter.
var xhttp = new XMLHttpRequest();
xhttp.responseType = 'blob';
xhttp.onload = function(e) {
var blob = xhttp.response;
callback(blob);
};
xhttp.open...
And now in your callback you will be able to create a blobURI directly from this blob.
function callback(blob) {
var url = URL.createObjectURL(blob);
...
Also, if all you want is to display this file, there is no point in creating a File from it, the only web API it would make a difference if it was a File and not just a Blob is Formdata.append method, and even there, it's not that useful.

Rails application works in local environment but in production I can't call the function because its not defined

I have a snippet that sends a http request to another site, but when it gets compiled in production I lose the ability to call on it and an undefined no method error. How do i make it so I can call the function from any page, without having to past it directly to every view that I want it at.
in my assets/javascript directory i have a 'js file' with the these lines
var foobar= {}
foobar.report = function(eventName){
var event = {event: {name:eventName}};
var request = new XMLHttpRequest();
request.open("POST", "http://localhost:3000/api/events", true)
request.setRequestHeader('Content-Type', 'application/json');
request.send(JSON.stringify(event));
};
then I have something like this to call it in the view
<script>foobar.report('about page loaded');</script>
Place your code inside (function() {});
(function() {
var foobar= {}
foobar.report = function(eventName){
var event = {event: {name:eventName}};
var request = new XMLHttpRequest();
request.open("POST", "http://localhost:3000/api/events", true)
request.setRequestHeader('Content-Type', 'application/json');
request.send(JSON.stringify(event));
};`enter code here`
});

how to instantiate new file object javascript

I'm having troubles instantiating a new file object in javascript.
Here's the general gist of what I'm trying to do. There is client side code that expecting a "file" type object. I need to access the file that's located on the server (game.smc), download it to the local machine and feed it to the client side code.
I did some research and found that creating a new blob object is the first step. But in the code below the blob object remains null and is never getting populated. Does the path in the xhr.open need to have the entire url? Maybe i'm missing an entire concept here not sure.
var blob = null;
var xhr = new XMLHttpRequest();
xhr.open("GET", "/Roms/game.smc");
xhr.responseType = "blob";
xhr.onload = function()
{
blob = xhr.response;
}
xhr.send();
Once I can get the blob object populated I can then do this to convert it to a file object.
function blobToFile(theBlob, fileName) {
theBlob.lastModifiedDate = new Date();
theBlob.name = fileName;
return theBlob;
}
This is what I ended up doing. Shows how to get the blob object as well as convert it to a file type.
function autoLoadGame(fileName) {
var gameLocation = '/Content/Roms/Snes/' + fileName;
var blob = null;
var xhr = new XMLHttpRequest();
xhr.open("GET", gameLocation, true);
xhr.onreadystatechange = function () {
if (xhr.readyState == XMLHttpRequest.DONE) {
var blob = xhr.response;
var file = new File([blob], fileName, { type: '', lastModified: Date.now() });
snes_readfile(file);
}
}
xhr.responseType = "blob";
xhr.send();
}

Getting blob gives 404 error

could someone prompt me - how to save "blob in memory" to a file using Java Script?
e.g. I have in the page next blob-image:
<img src="blob:https%3A//drive.google.com/851b979c-92e9-4ef2-9152-8935f7793630" class="g-img">
and I need to save this blob to a file (png/jpg).
The next code just gives:
GET blob:https%3A//drive.google.com/851b979c-92e9-4ef2-9152-8935f7793630 404 (Not Found)
so it seems, usual way to get the blobs doesn't work here.
Is there any workaround to save this blob-images from browser memory to a file, or, saying more exactly - to get them as a real blob using only "src" tag value?
Thank you.
var srcEl = evt.srcElement;
var CurI = document.getElementsByClassName('g-img');
[].forEach.call(CurI, function (el) {
var xhr = new XMLHttpRequest();
xhr.open('GET', el.src, true);
xhr.responseType = 'arraybuffer'; // xhr.responseType = 'blob';
xhr.onload = function(e) {
if (this.status == 200) {
var myBlob = this.response;
var reader = new window.FileReader();
reader.readAsDataURL(myBlob);
console.log(myBlob);
}
};
xhr.send();
console.log(el.src);
// saveAs(myBlob, 'my2image.png');
}
p.s. to use mediarecorder?

XMLHttpRequest detecting 404 (Not Found)

If the URL is correct (file.dat exists), this works great (the file length matches). If it is wrong I will see a very small file length and I will not see the xhr.onerror.
How can I detect that the URL was incorrect?
var xhr = new XMLHttpRequest()
xhr.responseType = "blob"
xhr.onload = ()=> {
var reader = new FileReader()
reader.onload = evt => {
var contents = new Buffer(evt.target.result, 'binary')
console.log('file len',contents.length)
}
reader.readAsBinaryString(xhr.response)
}
xhr.addEventListener("error", () => { console.error('xhr.onerror',e) })
xhr.open("GET", "file.dat")
xhr.send()
https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest
I do see a stacktrace in the console pointing to xhr.send()
GET http://localhost:8080/file.dat 404 (Not Found)
A try catch around both open and send does not catch any exceptions.
Files are served by WebpackDevServer (I hope that should not matter though).
You can check the status of the response object.
// Not using arrow function because I don't want the lexical `this`
xhr.onload = function() {
if (this.status === 404) {
// not found, add some error handling
return;
}
var reader = new FileReader()
reader.onload = evt => {
var contents = new Buffer(evt.target.result, 'binary')
console.log('file len',contents.length)
}
reader.readAsBinaryString(xhr.response)
}
Credit to https://developer.appcelerator.com/question/129410/xhr-request-cant-check-for-error-for-404-page-or-other-errors
Using https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest#xmlhttprequest-status:
XmlHttpRequest objects (you have one in the variable xhr) have a read-only property status that you can use to get the status text once it's loaded.

Categories

Resources