Is it possible to upload a text file to input in HTML/JS?
If you wish to go the client side route, you'll be interested in the HTML5 FileReader API. Unfortunately, there is not wide browser support for this, so you may want to consider who will be using the functionality. Works in latest Chrome and Firefox, I think.
Here's a practical example: http://www.html5rocks.com/en/tutorials/file/dndfiles/#toc-reading-files
And I also read here to find the readAsText
method: http://www.w3.org/TR/file-upload/#dfn-readAsText
I would do something like this (jQuery for brevity): http://jsfiddle.net/AjaDT/2/
Javascript
var fileInput = $('#files');
var uploadButton = $('#upload');
uploadButton.on('click', function() {
if (!window.FileReader) {
alert('Your browser is not supported');
return false;
}
var input = fileInput.get(0);
// Create a reader object
var reader = new FileReader();
if (input.files.length) {
var textFile = input.files[0];
// Read the file
reader.readAsText(textFile);
// When it's loaded, process it
$(reader).on('load', processFile);
} else {
alert('Please upload a file before continuing')
}
});
function processFile(e) {
var file = e.target.result,
results;
if (file && file.length) {
results = file.split("\n");
$('#name').val(results[0]);
$('#age').val(results[1]);
}
}
Text file
Jon
25
Upload text file and make JavaScript variable that text
Try below function, it will give you file content in "fileContent" variable:
function alertText() {
var file = document.getElementsByTagName("input")[0].value;
var reader = new FileReader();
reader.onload = function (evt) { //When file is loaded.
var fileContent = evt.target.result; //event.target.result is the file content
}
reader.readAsText(file, "UTF-8");
}
Uploading a text file in Flask and reading it in html
Thanks to the commenters on this post, I could come up with a fix to this. Initially, I was getting a b" as the only output after using only f.read()
.
When I used f.seek(0)
, I got the output of my text file but with a lot of encoding and formatting errors, including a new preceding b` followed by my output.
But adding content = f.read()
content = str(content, 'utf-8')
fixed most of that aswell.
So here goes the final solution-
def upload_source():
if request.method == 'POST':
# check if the post request has the file part
f = request.files['file']
if f.filename == "":
print("No file Name")
return redirect(request.url)
if not allowed_file(f.filename):
print("File extension not allowed!")
return redirect(request.url)
else:
full_filename = secure_filename(f.filename)
f.save(os.path.join(app.config['UPLOAD_FOLDER'], full_filename))
f.seek(0)
print("File saved")
content = f.read()
content = str(content, 'utf-8')
return render_template('source.html', text=content)
and don't forget the same old HTML -
<p> {{ text }} </p>
I hope this can help others as well. Thank you!
Javascript read a text file being uploaded through a form
Matti is correct, with HTML 4 you're out of luck.
However, with HTML 5 this is made possible by using the FileReader API. Currently support for this feature is limited to very recent versions of Chrome, Firefox and Opera. A similar feature exists in older versions of Firefox and this can also be done in older versions of Internet Explorer by using ActiveX. I would imagine that Google Gears also would allow this although I haven't looked into it.
The Javascript to do this would look like:
$( "#files" ).change( function( event )
{
var reader = new FileReader();
reader.onload( e ) { /* handle a file being loaded. contents in event.result */ };
reader.onerror( e ) { /* handle an error during the file reading */ };
var files = event.target.files;
for( var i = 0; i < files.length; i++ )
console.log(reader.readAsText( files[i] ));
});
Where #files is simply:
<input type="file" id="files" multiple />
get the data of uploaded file in javascript
you can use the new HTML 5 file api to read file contents
https://developer.mozilla.org/en-US/docs/Using_files_from_web_applications
but this won't work on every browser so you probably need a server side fallback.
Related Topics
Html Form Action and Onsubmit Issues
How to Re-Trigger a Webkit CSS Animation Via JavaScript
Adding Additional Data to Select Options Using Jquery
How to Save a Base64 Image to User'S Disk Using JavaScript
Select All Elements That Have a Specific Css, Using Jquery
How to Reload CSS Without Reloading the Page
Rails Js.Erb File Cannot Find Method "Render"
How to Copy to the Clipboard in JavaScript
How to Access Previous Promise Results in a .Then() Chain
Find HTML Label Associated With a Given Input
How to Bind Events on Ajax Loaded Content
How to Prevent JavaScript Injection Attacks Within User-Generated Html
Add Svg Element to Existing Svg Using Dom
Find All CSS Rules That Apply to an Element
Ios 8 Removed "Minimal-Ui" Viewport Property, Are There Other "Soft Fullscreen" Solutions