Read the contents of a "file" object?
So I have a "File" object (retrieved by handling file drag and drop from deskt开发者_StackOverflow社区op). I can send the files to the server with ajax, and then throw them back for javascript to handle them. But is it possible to read the contents of it without doing all this?
Here, play around with this fiddle. Drag any file to the box and use the variable file
.
I've already tried all of the methods of this object...no luck. Can you get the contents of the file you just dragged into the browser?
PS: I would send the files to the server like this:
var ajaxRequest = new XMLHttpRequest();
ajaxRequest.open("returnRawPostData.php");
ajaxRequest.send(file);
I might have missed something in the code above, but that's just because one doesn't use plain JS to do AJAX calls anymore.
Using the links from Martin Mally (thanks a lot!), I came up with this:
var file = e.dataTransfer.files[0],
read = new FileReader();
read.readAsBinaryString(file);
read.onloadend = function(){
console.log(read.result);
}
Where read.result
holds the contents of the file.
I think it's possible; check these two articles:
- https://developer.mozilla.org/en/Using_files_from_web_applications
- http://hacks.mozilla.org/2011/01/how-to-develop-a-html5-image-uploader/
They both manipulates with "dropped" file via JS/HTML before uploading to server. (e.g. picture resizing etc.) I hope it helps.
Most modern browsers can now use the Blob.text()
API, which provides a promise-based method of reading files.
Every item within a FileList (inputElement.files
) is an instance of a Blob, meaning we can call .text()
on any item within the FileList to read it as text.
This is asynchronous, and much simpler than setting up a FileReader and using events, if you're familiar with async code and promises.
async function readTextFromFileInput(input: HTMLInputElement): Promise<string | void> {
if (input.files?.length !== 1) {
// No file selected...
return;
}
return await input.files[0].text();
}
I just use
let reader = new FileReader();
reader.readAsText(your_file_object);
reader.onload = function() {
console.log(reader.result); // prints file contents
};
精彩评论