Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read the contents of a "file" object?

So I have a "File" object (retrieved by handling file drag and drop from desktop). 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.

like image 576
JCOC611 Avatar asked Mar 05 '11 02:03

JCOC611


People also ask

How do you read the contents of a file in JavaScript?

To read a file, use FileReader , which enables you to read the content of a File object into memory. You can instruct FileReader to read a file as an array buffer, a data URL, or text.

How do you open a file object?

File object has the following methods that we can use to accessing a file: A file can be opened with a built-in function called open() . This function takes in the file's path and the access mode and returns a file object. Read More: Open a file in Python.

What do you mean by file object in Python?

A file object allows us to use, access and manipulate all the user accessible files. One can read and write any such files. When a file operation fails for an I/O-related reason, the exception IOError is raised.


2 Answers

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.

like image 76
JCOC611 Avatar answered Oct 02 '22 19:10

JCOC611


I think it's possible; check these two articles:

  1. https://developer.mozilla.org/en/Using_files_from_web_applications
  2. 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.

like image 35
Martin Maly Avatar answered Oct 02 '22 19:10

Martin Maly