How to convert a File to a Blob in Javascript without FileReader? - javascript

I'm trying to convert a File into a Blob without using FileReader. I can't use FileReader because the latest version of Typescript (which I must use) doesn't accept a File as the parameter to fileReader.readAsArrayBuffer().
Using FileReader I can do it as follows:
var reader = new FileReader();
reader.onloadend = function(e) {
new Blob([ this.result ], { type: "image/jpeg" } );
};
reader.readAsArrayBuffer(file);
How can I achieve the same result without FileReader?

You can always augment the declaration in lib.d.ts with an overload accepting a File.
For example, create a file named globals.d.ts with the following content
interface FileReader {
readAsArrayBuffer(file: File): void;
}
That said, if the declaration was changed, I would be wary of this behavior as some environments likely do not support it.

Related

How to write javascript's FileReader() reader.result object to a file at server side using python?

I'm writing a Jupyterlab extension, in one of its functionality, I'm trying to write file upload functionality which reads the user-selected file and write back to the server. To accomplish the job it uses javascript's FileReader API and then passes the object to python using JSON.stringify(). However, I'm able to write a file on the server side using a test string but not able to write a file using the file content due to the object compatibility issue.
This code contains both javascript and server-side code.
readFile(data) {
let file = data.files[0];
let reader = new FileReader();
reader.readAsText(file);
reader.onload = async function() {
console.log(reader.result);
console.log('OK');
var InitialData = await KernelSideDataObjects(`import json\nfile = open('test.txt', 'wb+')\nfile.write('test')`);
//var InitialData = await KernelSideDataObjects(`import json\nfile = open('test.txt', 'wb+')\nfile.write(${JSON.stringify(reader.result)})`);
// console.log(reader.readAsDataURL(file))
};
reader.onerror = function() {
console.log(reader.error);
};
}
How can I translate or decode reader.result into a python-compatible manner to write file content in a file?
Thanks

Angular 7+: how to only allow upload of files with content in utf-8?

I am using angular 7+, I have a simple function to do the upload files and read their contents, but I would like to know how to identify the encode of document content, to only allow documents with encode utf-8.
async uploadFile(event) {
var document;
var reader = new FileReader();
let file = event.target.files[0];
reader.onload = ((file: any) => {
return (e: any) => {
document.description = e.srcElement.result;
document.title = title;
document.fileName = file.name;
}
})(file);
reader.readAsText(file);
}
Thanks.
Here is the documentation of FileReader.readAsText()
instanceOfFileReader.readAsText(blob[, encoding]);
To ensure that the uploaded file is in UTF-8, do :
instanceOfFileReader.readAsText(blob, 'UTF-8');
Know that UTF-8 is the default setting, so it should work, you could also do :
instanceOfFileReader.readAsText(blob);
If the encoding is not UTF-8, the read should fail. I've seen no documentation at all about that, considering this as the normative documentation.
You should try to upload a file having an other encoding to be sure of it.
There is no attribute called encoding or anything like it in FileReader documentation
There is no bulletproof technique to get the encoding of a text file. Anyhow, a library called jschardet tries to achieve this goal though.
function read(f) {
var reader = new FileReader();
reader.readAsText(f);
reader.onload = function(e) {
console.log(jschardet.detect(reader.result))
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jschardet/2.1.0/jschardet.min.js"></script>
<input type="file" onchange="read(this.files[0])"></input>

Is it possible to overwrite existing local xml file with javascript?

I have been successfully using FileReader to parse some XML data to HTML page from a local file. If I make changes to the DOM, I can successfully parse the data back to an XML file, but if I try to overwrite the file that was used to read, it does not successfully download. If I save the file with a different name, it successfully downloads.
I use FileReader like this from a browse/input selector:
function handleFileSelection(evt) {
var files = evt.target.files;
var url = window.URL.createObjectURL(files[0]);
reader = new FileReader();
reader.onload = function (e) {
Then if I make changes, I save the data like this:
var blob = new Blob(
arrayOfUnits,
{ type: "text/xml" }
);
window.navigator.msSaveBlob(blob, 'Units.xml');
I feel like the FileReader either has the file locked, or perhaps JavaScript cannot overwrite local files?
I have tried using: FileReader.abort() which seems to be like FileReader.close() in java, but this didn't fix my issue.
Any help is appreciated, I am new to using JavaScript with local file system.
FileReader won't write to the file system. You need FileWriter to do so.

How to download a file generated with JavaScript, avoiding automatic opening of Chome?

I am developing a JavaScript little webmail.
I receive from the server a Base64-encoded string, that represents a file (it could be whatever type). I decode the string, a map it to a Uint8Array, and with it, I generate a Blob object with I create a data URI with
FileReader.readAsDataURL(blob)
Until here is pretty straightforward, but I am having problem with the download part.
I put the DataURI in
window.open(dataURI)
But chrome opens a new window and display my image, or my text. But I need to avoid this behaviour, and download the file instead.
I have red that this could be done with Content-Disposition "attachment" but I am not sure if it is my case, because I am generating the file from a string from the server.
Anyone who can help me understand?
Did you try to use "saveAs" ?
saveAs(blob, "hello.zip");
In the case you need wide browser support you could try polifill. More information
I am pretty sure you can set the type of the blob
var blob = new Blob(["Hello world!"], { type: "application/download" });
Edit:
without FileSaver.js:
var blob = new Blob(["Hi stack"], {type: 'application/download'});
var reader = new FileReader();
reader.onloadend = function(e) {
window.open(reader.result);
}
reader.readAsDataURL(blob);
Edit:
Documentation and browser support information ("Browser compatibility" tab):
FileReader
Blob

How to get data from uploaded input File object

In my Javascript, I have a File object using input type file, so I can get file name, file size, etc. How do I get the File's actual data?
You need to address the raw data by looking back to the Blob object. See here:
https://developer.mozilla.org/en-US/docs/Web/API/Blob
You can use a FileReader object, e.g.
function readFile(thefile) {
var reader = new FileReader();
reader.onload = function(e) {
alert(e.target.result);
};
reader.readAsText(thefile);
}

Categories