Parsing error in a FileReader onload function - javascript

For some reason I am getting an error with my FileReader unload function. The error is Parsing error: Invalid left-hand side in assignment expression I looked in to what that means to according to MDN web docs: "invalid assignment left-hand side" occurs when there was an unexpected assignment somewhere. For example, a single "=" sign was used instead of "==" or "===". I don't see how this would be a error.
var fileInput = files[0];
var audioCtx = new AudioContext(files[0]);
var reader1 = new FileReader();
reader1.onload() = function (ev) { //error here
//decode audio
audioCtx.decodeAudioData(ev.target.result).then(function(buffer) {
reader1.readAsArrayBuffer(fileInput.files[0]);
})
}

onload is a property, not a method.
reader1.onload = function (ev) {
...
}

Related

Blazor WebbAssembly exception when calling javascript function?

I have a C# function that is invoking a Javascript function, this is the C# function:
await _jsRuntime.InvokeVoidAsync("setMediaUsingStreaming", type, dotnetImageStream);
And this is the Javascript function:
async function setMediaUsingStreaming(fileType, fileStream) {
try {
const arrayBuffer = await fileStream.arrayBuffer();
const blob = new Blob([arrayBuffer]);
const url = URL.createObjectURL(blob);
var newHTMLElement;
var fileHTMLElement = document.getElementById('fileDisplay');
if (fileType == "image") {
newHTMLElement = document.createElement('img');
}
else {
newHTMLElement = document.createElement('video');
var attribute = document.createAttribute('controls');
newHTMLElement.setAttributeNode(attribute);
}
fileHTMLElement.appendChild(newHTMLElement);
newHTMLElement.src = url;
} catch (Exception)
{
console.log(Exception)
}
}
When the C# function is invoking the Javascript function I receive this error :
blazor.webassembly.js:1 Uncaught (in promise) Error:
Microsoft.JSInterop.JSException: Cannot set properties of null
(setting 'src') TypeError: Cannot set properties of null (setting
'src')
The weird thing is that I receive this error when I run the app in publish mode (withouth a debugger) but it works perfectly in debug mode. The catch from the javascript function is not hit when I receive this error, it seems that is the C# method that is throwing it.
I know what the error is saying, that the url variable is null, but I don't understand why is null, and why it works on debug mode.
Do you have any ideas ?

FileReader error : Cannot read property 'size' of undefined

Good Day,
I have this code:
function loadFile() {
var fileToLoad = document.getElementById("loadMe").files[0];
var fileStart = 0;
var fileEnd = fileToLoad.size - 1;
var fileReader = new FileReader();
fileReader.onload = function(fileLoadedEvent) {
var textFromFileLoaded = fileLoadedEvent.target.result;
var string = textFromFileLoaded.split('&');
pleaseDoSomethingWithTheContentOfTheFile(textFromFileLoaded);
};
fileReader.readAsText(fileToLoad, "UTF-8");
}
I have an error :
Uncaught TypeError: Cannot read property 'size' of undefined
at loadFile
According to this post there is no index [0]... But when I remove that, I still have the same error. Is this something coming from this code, or does it look good ?
Thanks in advance! :)
double check whether the file is selected before calling loadFile function.
also use below code checking the size
if (!fileToLoad) {
alert('Pleae select file');
return;
}

Javascript: Filereader onloadend with TypeError

Actually I tried to read a file in ionic 2 using a filereader object. But instead of firing the onloadend function I can see all my wanted data in the console by adding the whole reader into the output, but I'm not able to get this data.
Here's my code:
loadFile(path) {
this.platform.ready().then(() => {
window.resolveLocalFileSystemURL(path, gotFile, fail);
function fail() {
console.log('fail()');
}
fileEntry.file(function(file) {
var reader = new FileReader();
reader.onloadend = function(evt) {
console.log('onload');
}
reader.readAsText(file);
console.log(reader);
})
}
});
In the console I can see under onloadend inside the caller object under arguments and under caller the following message:
Exception: TypeError: 'caller' and 'arguments' are restricted function properties and cannot be accessed in this context. at Function.remoteFunction (:3:14) at Object.InjectedScript.callFunctionOn (:724:66)
How can I fix this problem? Thanks in advance!

How to change emscripten browser input method from window.prompt to something more sensible?

I have a C++ function which once called consumes input from stdin. Exporting this function to javascript using emscripten causes calls to window.prompt.
Interacting with browser prompt is really tedious task. First of all you can paste only one line at time. Secondly the only way to indicate EOF is by pressing 'cancel'. Last but not least the only way (in case of my function) to make it stop asking user for input by window.prompt is by checking the checkbox preventing more prompts to pop up.
For me the best input method would be reading some blob. I know I can hack library.js but I see some problems:
Reading blob is asynchronous.
To read a blob, first you have to open a file user has to select first.
I don't really know how to prevent my function from reading this blob forever - there is no checkbox like with window.prompt and I'm not sure if spotting EOF will stop it if it didn't in window.prompt case (only checking a checkbox helped).
The best solution would be some kind of callback but I would like to see sime hints from more experienced users.
A way would be to use the Emscripten Filesystem API, for example by calling FS.init in the Module preRun function, passing a custom function as the standard input.
var Module = {
preRun: function() {
function stdin() {
// Return ASCII code of character, or null if no input
}
var stdout = null; // Keep as default
var stderr = null; // Keep as default
FS.init(stdin, stdout, stderr);
}
};
The function is quite low-level: is must deal with one character at a time. To read some data from a blob, you could do something like:
var data = new Int8Array([1,2,3,4,5]);
var blob = new Blob([array], {type: 'application/octet-binary'});
var reader = new FileReader();
var result;
reader.addEventListener("loadend", function() {
result = new Int8Array(reader.result);
});
var i = 0;
var Module = {
preRun: function() {
function stdin() {
if (if < result.byteLength {
var code = result[i];
++i;
return code;
} else {
return null;
}
}
var stdout = null; // Keep as default
var stderr = null; // Keep as default
FS.init(stdin, stdout, stderr);
}
};
Note (as you have hinted), due to the asynchronous nature of the reader, there could be a race condition: the reader must have loaded before you can expect the data at the standard input. You might need to implement some mechanism to avoid this in a real case. Depending on your exact requirements, you could make it so the Emscripten program doesn't actually call main() until you have the data:
var fileRead = false;
var initialised = false;
var result;
var array = new Int8Array([1,2,3,4,5]);
var blob = new Blob([array], {type: 'application/octet-binary'});
var reader = new FileReader();
reader.addEventListener("loadend", function() {
result = new Int8Array(reader.result);
fileRead = true;
runIfCan();
});
reader.readAsArrayBuffer(blob);
var i = 0;
var Module = {
preRun: function() {
function stdin() {
if (i < result.byteLength)
{
var code = result[i];
++i;
return code;
} else{
return null;
}
}
var stdout = null;
var stderr = null;
FS.init(stdin, stdout, stderr);
initialised = true;
runIfCan();
},
noInitialRun: true
};
function runIfCan() {
if (fileRead && initialised) {
// Module.run() doesn't seem to work here
Module.callMain();
}
}
Note: this is a version of my answer at Providing stdin to an emscripten HTML program? , but with focus on the standard input, and adding parts about passing data from a Blob.
From what I understand you could try the following:
Implement selecting a file in Javascript and access it via Javascript Blob interface.
Allocate some memory in Emscripten
var buf = Module._malloc( blob.size );
Write the content of your Blob into the returned memory location from Javascript.
Module.HEAPU8.set( new Uint8Array(blob), buf );
Pass that memory location to a second Emscripten compiled function, which then processes the file content and
Deallocate allocated memory.
Module._free( buf );
Best to read the wiki first.

HTML 5 File API 0x80004003

Hi i am using the JS HTML5 File API to handle file uploads to my server.
I am getting the following error in Aurora(Fire Fox Bleeding edge builds)
NS_ERROR_INVALID_POINTER: Component returned failure code: 0x80004003 (NS_ERROR_INVALID_POINTER) [nsIDOMFileReader.readAsBinaryString]
function readBlob(opt_startByte, opt_stopByte,file,partNo) {
var start = parseInt(opt_startByte);
var stop = parseInt(opt_stopByte);
var reader = new FileReader();
var totalParts = parseInt(file.size/MAX_READ);
if((file.size % MAX_READ) !== 0){
totalParts++;
}
// If we use onloadend, we need to check the readyState.
reader.onloadend = function(evt) {
if (evt.target.readyState == FileReader.DONE) {
//var contents = reader.result;
postFilePart(partNo,contents,totalParts,escape(file.name))// DONE == 2
}
};
if (file.webkitSlice) {
var blob = file.webkitSlice(start, stop);
} else if (file.mozSlice) {
var blob = file.mozSlice(start, stop);
}
reader.readAsBinaryString(blob);
}
the error is occurring at this line
reader.readAsBinaryString(blob);
i have tried mozSlice and Slice
if (file.mozSlice) {
var blob = file.mozSlice(start, stop);
}
and it gave me the same results. it might not be the best idea to use HTML 5 API yet as this may cause issues with other browsers as well.
does anyone have a work around to get the same functionality or how i can resolve this particular error
Solved the issue it it was rerunning the reader code with incorrect parameters due to a mistake on the calling method
https://bugzilla.mozilla.org/show_bug.cgi?id=725289
rather use slice vs mozSlice

Categories

Resources