How to get the contents of a file from a form?

How to get the contents of an HTML form form file? Here is an example of what I'm working with. All this outputs 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 like the solution is hard to implement this way. What I'm trying to execute is send a file to a python script on my web server. This is my first time I try, so suggestions are welcome. I suppose I can put a python script in my cgi folder and pass values ​​to it using something like ...

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

Would it be a better solution to send the contents of a file to a web server rather than using javacript to open it directly using FileReader?

+5
source share
4 answers

FileReader.

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]);
    }
}

( Chrome Firefox)

+3

, .

+1

Yes. Replace the input line as below, then it will work :)

<input type="file" ACCEPT="text/html" name="whocares" id="idexample" />
0
source

As Neil said, this is for sending files to the server.

Another thing worth mentioning regarding existing code. Your form should use POST to submit data. You have not abandoned the method, but by default GET

<form name = "form_input" enctype="multipart/form-data" method="POST> 
0
source

All Articles