Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how do I get the file content from a form?

How do I get the contents of a file form a HTML form? Here is an example of what I'm working with. All it does it output something like "C:\Fake Path\nameoffile

<html>
<head>

<script type="text/javascript">
    function doSomething(){
        var fileContents = document.getElementById('idexample').value;
        document.getElementById('outputDiv').innerHTML = fileContents;
    }
</script>

</head>
<body >

<form name = "form_input" enctype="multipart/form-data">

<input type="file" name="whocares" id="idexample" />
<button type="button" onclick="doSomething()">Enter</button>

</form>

<div id="outputDiv"></div>

</body>
</html>

EDIT: It seems the solution is difficult to implement this way. What I'm trying to accomplish is sending a file to a python script on my webserver. This is my first time trying this sort of thing so suggestions are welcome. I supposes I could put the python script in my cgi folder and pass the values to it using something like...

/cgi/pythonscript.py?FILE_OBJECT=fileobjecthere&OTHER_VARIABLES=whatever

Would this be a better solution for sending file content to a webserver rather than having javacript open it directly using FileReader?

like image 665
b10hazard Avatar asked Dec 27 '11 13:12

b10hazard


1 Answers

You can actually do that with the new FileReader Object.

Try this working example

function doSomething()
{
    var file = document.getElementById('idexample');

    if(file.files.length)
    {
        var reader = new FileReader();

        reader.onload = function(e)
        {
            document.getElementById('outputDiv').innerHTML = e.target.result;
        };

        reader.readAsBinaryString(file.files[0]);
    }
}

(works with the newest versions of Chrome and Firefox)

like image 193
copy Avatar answered Oct 13 '22 18:10

copy