I have a html code like this:
<input type="file" id="up" />
<input type="submit" id="btn" />
And I have a JSON file like this:
{
"name": "John",
"family": "Smith"
}
And a simple JavaScript function:
alert_data(name, family)
{
alert('Name : ' + name + ', Family : '+ family)
}
Now I want to call alert_data() with name and family that stored in JSON file which uploaded using my HTML input.
Is there any way to use an HTML5 file reader or something else?
I'm not using server-side programming, all of them are client-side.
You will need an HTML5 browser, but this is possible.
(function(){
function onChange(event) {
var reader = new FileReader();
reader.onload = onReaderLoad;
reader.readAsText(event.target.files[0]);
}
function onReaderLoad(event){
console.log(event.target.result);
var obj = JSON.parse(event.target.result);
alert_data(obj.name, obj.family);
}
function alert_data(name, family){
alert('Name : ' + name + ', Family : ' + family);
}
document.getElementById('file').addEventListener('change', onChange);
}());
<input id="file" type="file" />
<p>Select a file with the following format.</p>
<pre>
{
"name": "testName",
"family": "testFamily"
}
</pre>
Since all answers seem unnecessarily complex, here's a simple async function that returns the file contents as an Object:
async function parseJsonFile(file) {
return new Promise((resolve, reject) => {
const fileReader = new FileReader()
fileReader.onload = event => resolve(JSON.parse(event.target.result))
fileReader.onerror = error => reject(error)
fileReader.readAsText(file)
})
}
const object = await parseJsonFile(file)
Here's a shorthand version of Sam Greenhalghs answer that works for me.
$(document).on('change', '.file-upload-button', function(event) {
var reader = new FileReader();
reader.onload = function(event) {
var jsonObj = JSON.parse(event.target.result);
alert(jsonObj.name);
}
reader.readAsText(event.target.files[0]);
});
<input class='file-upload-button' type="file" />
Yep! It can be done with HTML5 FileReader. And it's actually pretty simple.
Save the json as a .js file and load it in my example
{
"name": "John",
"family": "Smith"
}
This is where the magic happens:
$("#up").change(function(event){
var uploadedFile = event.target.files[0];
if(uploadedFile.type !== "text/javascript" && uploadedFile.type !== "application/x-javascript") {
alert("Wrong file type == " + uploadedFile.type);
return false;
}
if (uploadedFile) {
var readFile = new FileReader();
readFile.onload = function(e) {
var contents = e.target.result;
var json = JSON.parse(contents);
alert_data(json);
};
readFile.readAsText(uploadedFile);
} else {
console.log("Failed to load file");
}
});
function alert_data(json)
{
alert('Name : ' + json.name + ', Family : '+ json.family)
}
Fiddle link with this code: http://jsfiddle.net/thomas_kingo/dfej7p3r/3/
(The uploadedFile.type check is only tested in Chrome and firefox)
Related
So in HTML I can do something this:
<input type="file" id="upload" accept="text" multiple/>
Then I can access the files uploaded in JavaScript like this whenever the input changes:
document.getElementById('upload').onchange = function(){
const uFiles = this.files;
console.log(uFiles);
}
How would I go about doing that with ReactJS? So far, I've tried using the same approach I would use for HTML and JavaScript but I get the response that uFiles is undefined rather than a FileList object.
In my React Render:
<input onChange={this.doFunc} id="upload" type="file" accept="text" multiple />
In my React class:
doFunc = () => {
const uFiles = this.files;
console.log(uFiles);
}
I think you have to use event.
doFunc = e => {
const uFiles = e.target.files;
console.log(uFiles);
}
function handleUploadChange(e)
{
const file = e.target.files[0];
if ( !file )
{
return;
}
const reader = new FileReader();
reader.readAsBinaryString(file);
reader.onload = () => {
console.log(reader.result);
console.log(file.type);
};
reader.onerror = function () {
console.log("error on load image");
};
}
I'm implementing a check in which I dont want to upload the image which has size greater than 4MB. I'm using file reader and new image(). I've the image size and width. But how can I get the filesize.
function previewImage(element) {
var reader = new FileReader();
reader.onload = function (event) {
seAddArtist.imageSource = event.target.result;
$scope.$apply();
};
// when the file is read it triggers the onload event above.
reader.readAsDataURL(element.files[0]);
}
var img = new Image();
img.onload = function () {
alert(this.width + 'x' + this.height);
}
I am implementing these two combine but how can i check the size of image?
FileReader (FileReader API) itself does not provide the size of an file. You need to use file (file API) instead:
function previewImage(element) {
var reader = new FileReader();
reader.onload = function(event) {
seAddArtist.imageSource = event.target.result;
$scope.$apply();
};
// when the file is read it triggers the onload event above.
reader.readAsDataURL(element.files[0]);
//log / access file size in bytes
console.log(element.files[0].size + ' Bytes');
//log / access file size in Mb
console.log(element.files[0].size/1024/1024 + ' MB');
if (element.files[0].size/1024/1024 > 4) {
console.log('file is bigger than 4MB);
}
}
That might be what you want:
var size = files[0].size;
You can check the file size before submitting:
<!doctype HTML>
<html>
<head>
<script>
function checkFileSize() {
var size = document.getElementById("fileSelector").files[0].size;
alert("file size: " + size);
}
</script>
</head>
<body>
<input id="fileSelector" type="file" onchange="checkFileSize()"/>
<input type="submit" />
</body>
</html>
This is working code to get file size. you will get file size in KB.
<input id="file" type="file">
<img id="filerendered" src="">
and in script tag
document.getElementById('file').onchange = function (event) {
var targetn = event.target || window.event.srcElement,
files = targetn.files;
// FileReader here
if (FileReader && files && files.length) {
var thisReader = new FileReader();
alert("your file size "+ (files[0].size)/1024 + "kb")
thisReader.onload = function () {
document.getElementById("filerendered").src = thisReader.result;
}
thisReader.readAsDataURL(files[0]);
}
// for Not supported case
else {
// not supported
}
}
How can I upload a JSON file on some click on a button on my web page say "import", and use it to store in a variable to use and update it using JavaScript.
I have gone through the other posts but could not find any answer.
I am saving the JSON variable using this function:
function save(filename, data){
if(!data) {
alert('error : No data')
return;
}
if(typeof data === "object"){
data = JSON.stringify(data, undefined, 4)
}
var blob = new Blob([data], {type: 'text/json'}),
e = document.createEvent('MouseEvents'),
a = document.createElement('a')
a.download = filename
a.href = window.URL.createObjectURL(blob)
a.dataset.downloadurl = ['text/json', a.download, a.href].join(':')
e.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null)
a.dispatchEvent(e)
}
This is working fine and it downloads the file on clicking another button say "export".
How upload this file back and make a JSON variable of this file data?
Without server side code, your best approach may be to provide a textarea element for the user to copy/paste the JSON into, and then parse it using JSON.parse.
You could even go as far as to use something like Ace Editor to provide syntax highlighting for JSON - you can see it in action on the Ace Editor Kitchen Sink Demo - select JSON from the dropdown list in the top left.
Edit:
Turns out I was wrong. Here is a fiddle demonstrating the FileReader in use, which is exactly what you need:
https://jsfiddle.net/Ln37kqc0/
Here is the code:
Javascript:
document.getElementById('import').onclick = function() {
var files = document.getElementById('selectFiles').files;
console.log(files);
if (files.length <= 0) {
return false;
}
var fr = new FileReader();
fr.onload = function(e) {
console.log(e);
var result = JSON.parse(e.target.result);
var formatted = JSON.stringify(result, null, 2);
document.getElementById('result').value = formatted;
}
fr.readAsText(files.item(0));
};
HTML:
<input type="file" id="selectFiles" value="Import" /><br />
<button id="import">Import</button>
<textarea id="result"></textarea>
I have got a way to use the uploaded json file, here is the way i found.
$("#inputFile").change(function(e) {
onChange(e);
});
function onChange(event) {
var reader = new FileReader();
reader.onload = onReaderLoad;
reader.readAsText(event.target.files[0]);
}
function onReaderLoad(event){
//alert(event.target.result);
var obj = JSON.parse(event.target.result);
alert(obj);
}
Basic upload File:
<input id="contentFile" type="file" accept="application/json" />
document.getElementById('contentFile').onchange = function(evt) {
try {
let files = evt.target.files;
if (!files.length) {
alert('No file selected!');
return;
}
let file = files[0];
let reader = new FileReader();
const self = this;
reader.onload = (event) => {
console.log('FILE CONTENT', event.target.result);
};
reader.readAsText(file);
} catch (err) {
console.error(err);
}
}
[2021] Promise based approach
As mentioned here, you can make use of the newer blob api to easily get the file's value via:
await blob.text()
const getJsonUpload = () =>
new Promise(resolve => {
const inputFileElement = document.createElement('input')
inputFileElement.setAttribute('type', 'file')
inputFileElement.setAttribute('multiple', 'true')
inputFileElement.setAttribute('accept', '.json')
inputFileElement.addEventListener(
'change',
async (event) => {
const { files } = event.target
if (!files) {
return
}
const filePromises = [...files].map(file => file.text())
resolve(await Promise.all(filePromises))
},
false,
)
inputFileElement.click()
})
document.getElementById('upload-button').onclick = async () => {
const jsonFiles = await getJsonUpload()
console.log({jsonFiles})
}
<button id="upload-button">
Upload
</button>
Try this, works perfect
handleUploadFile = async(doc) => {
let file = doc.target.files[0]
let reader = new FileReader(file)
// await reader.readAsDataURL(file)
reader.readAsText(file)
reader.onload = async(e) => {
let aaa = e.target.result
let content = await JSON.parse(aaa)
console.log(content)
}
}
With the newer Blob API, the current top answer can be simplified by skipping the FileReader:
document.getElementById('import').onclick = function() {
var files = document.getElementById('selectFiles').files;
console.log(files);
if (files.length <= 0) {
return false;
}
files[0].text().then(function(text) {
console.log(text);
var result = JSON.parse(text);
var formatted = JSON.stringify(result, null, 2);
document.getElementById('result').value = formatted;
})
};
To explain the code a little: files[0] itself is a File object, which inherits from Blob, so files[0].text() is an asynchronous function that reads the content of the file into a string.
You may want to add the draggable option
Firs create your HTML
<div class="drag" id="drag_area">
<input class="box_file disabled" type="file" name="files[]" id="file" data-multiple-caption="{count} files selected" multiple />
<label for="file"><strong>Choose save file</strong><span class="box__dragndrop"> or drag it here</span>.</label>
</div>
Than write out your JS
$("#drag_area").on('drag dragstart dragend dragover dragenter dragleave drop', function (e) {
e.preventDefault();
e.stopPropagation();
})
.on('dragover dragenter', function () {
$("#drag_area").addClass('dr_active');
// this is needed if you wish to style your drag area on drag events
})
.on('dragleave dragend drop', function () {
$("#drag_area").removeClass('dr_active');
// this is needed if you wish to style your drag area on drag events
})
.on('drop', function (e) {
let droppedFiles = e.originalEvent.dataTransfer.files;
let reader = new FileReader()
reader.readAsDataURL(droppedFiles[0])
reader.onloadend = function () {
$.ajax({
url: reader.result,
success: function (data) {
console.log(JSON.parse(data)); // This is your JSON
},
error: function (request, error) {
cliLog(2, "Upload", "Cant upload save file")
}
});
}
}),
I'd made a more general approach with support to customize upload button title and callback when load is done:
function uploadJson(id, callback) {
document.getElementById(id).onchange = function(evt) {
try {
let files = evt.target.files;
if (!files.length) {
alert('No file selected!');
return;
}
let file = files[0];
let reader = new FileReader();
const self = this;
reader.onload = (event) => {
callback(event.target.result);
};
reader.readAsText(file);
} catch (err) {
console.error(err);
}
}
}
uploadJson('importJson', function (json) {
console.log(json);
});
<button onclick="document.getElementById('importJson').click()">import json</button>
<input id="importJson" value="import json" type="file" accept="application/json" style="display:none" />
I am trying to load a text file into my JavaScript file and then read the lines from that file in order to get information, and I tried the FileReader but it does not seem to be working. Can anyone help?
function analyze(){
var f = new FileReader();
f.onloadend = function(){
console.log("success");
}
f.readAsText("cities.txt");
}
Yeah it is possible with FileReader, I have already done an example of this, here's the code:
<!DOCTYPE html>
<html>
<head>
<title>Read File (via User Input selection)</title>
<script type="text/javascript">
var reader; //GLOBAL File Reader object for demo purpose only
/**
* Check for the various File API support.
*/
function checkFileAPI() {
if (window.File && window.FileReader && window.FileList && window.Blob) {
reader = new FileReader();
return true;
} else {
alert('The File APIs are not fully supported by your browser. Fallback required.');
return false;
}
}
/**
* read text input
*/
function readText(filePath) {
var output = ""; //placeholder for text output
if(filePath.files && filePath.files[0]) {
reader.onload = function (e) {
output = e.target.result;
displayContents(output);
};//end onload()
reader.readAsText(filePath.files[0]);
}//end if html5 filelist support
else if(ActiveXObject && filePath) { //fallback to IE 6-8 support via ActiveX
try {
reader = new ActiveXObject("Scripting.FileSystemObject");
var file = reader.OpenTextFile(filePath, 1); //ActiveX File Object
output = file.ReadAll(); //text contents of file
file.Close(); //close file "input stream"
displayContents(output);
} catch (e) {
if (e.number == -2146827859) {
alert('Unable to access local files due to browser security settings. ' +
'To overcome this, go to Tools->Internet Options->Security->Custom Level. ' +
'Find the setting for "Initialize and script ActiveX controls not marked as safe" and change it to "Enable" or "Prompt"');
}
}
}
else { //this is where you could fallback to Java Applet, Flash or similar
return false;
}
return true;
}
/**
* display content using a basic HTML replacement
*/
function displayContents(txt) {
var el = document.getElementById('main');
el.innerHTML = txt; //display output in DOM
}
</script>
</head>
<body onload="checkFileAPI();">
<div id="container">
<input type="file" onchange='readText(this)' />
<br/>
<hr/>
<h3>Contents of the Text file:</h3>
<div id="main">
...
</div>
</div>
</body>
</html>
It's also possible to do the same thing to support some older versions of IE (I think 6-8) using the ActiveX Object, I had some old code which does that too but its been a while so I'll have to dig it up I've found a solution similar to the one I used courtesy of Jacky Cui's blog and edited this answer (also cleaned up code a bit). Hope it helps.
Lastly, I just read some other answers that beat me to the draw, but as they suggest, you might be looking for code that lets you load a text file from the server (or device) where the JavaScript file is sitting. If that's the case then you want AJAX code to load the document dynamically which would be something as follows:
<!DOCTYPE html>
<html>
<head><meta charset="utf-8" />
<title>Read File (via AJAX)</title>
<script type="text/javascript">
var reader = new XMLHttpRequest() || new ActiveXObject('MSXML2.XMLHTTP');
function loadFile() {
reader.open('get', 'test.txt', true);
reader.onreadystatechange = displayContents;
reader.send(null);
}
function displayContents() {
if(reader.readyState==4) {
var el = document.getElementById('main');
el.innerHTML = reader.responseText;
}
}
</script>
</head>
<body>
<div id="container">
<input type="button" value="test.txt" onclick="loadFile()" />
<div id="main">
</div>
</div>
</body>
</html>
This can be done quite easily using javascript XMLHttpRequest() class (AJAX):
function FileHelper()
{
FileHelper.readStringFromFileAtPath = function(pathOfFileToReadFrom)
{
var request = new XMLHttpRequest();
request.open("GET", pathOfFileToReadFrom, false);
request.send(null);
var returnValue = request.responseText;
return returnValue;
}
}
...
var text = FileHelper.readStringFromFileAtPath ( "mytext.txt" );
Javascript doesn't have access to the user's filesystem for security reasons. FileReader is only for files manually selected by the user.
(fiddle:
https://jsfiddle.net/ya3ya6/7hfkdnrg/2/ )
Usage
Html:
<textarea id='tbMain' ></textarea>
<a id='btnOpen' href='#' >Open</a>
Js:
document.getElementById('btnOpen').onclick = function(){
openFile(function(txt){
document.getElementById('tbMain').value = txt;
});
}
Js Helper functions
function openFile(callBack){
var element = document.createElement('input');
element.setAttribute('type', "file");
element.setAttribute('id', "btnOpenFile");
element.onchange = function(){
readText(this,callBack);
document.body.removeChild(this);
}
element.style.display = 'none';
document.body.appendChild(element);
element.click();
}
function readText(filePath,callBack) {
var reader;
if (window.File && window.FileReader && window.FileList && window.Blob) {
reader = new FileReader();
} else {
alert('The File APIs are not fully supported by your browser. Fallback required.');
return false;
}
var output = ""; //placeholder for text output
if(filePath.files && filePath.files[0]) {
reader.onload = function (e) {
output = e.target.result;
callBack(output);
};//end onload()
reader.readAsText(filePath.files[0]);
}//end if html5 filelist support
else { //this is where you could fallback to Java Applet, Flash or similar
return false;
}
return true;
}
my example
<html>
<head>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.11.3/themes/smoothness/jquery-ui.css">
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script src="http://code.jquery.com/ui/1.11.3/jquery-ui.js"></script>
</head>
<body>
<script>
function PreviewText() {
var oFReader = new FileReader();
oFReader.readAsDataURL(document.getElementById("uploadText").files[0]);
oFReader.onload = function(oFREvent) {
document.getElementById("uploadTextValue").value = oFREvent.target.result;
document.getElementById("obj").data = oFREvent.target.result;
};
};
jQuery(document).ready(function() {
$('#viewSource').click(function() {
var text = $('#uploadTextValue').val();
alert(text);
//here ajax
});
});
</script>
<object width="100%" height="400" data="" id="obj"></object>
<div>
<input type="hidden" id="uploadTextValue" name="uploadTextValue" value="" />
<input id="uploadText" style="width:120px" type="file" size="10" onchange="PreviewText();" />
</div>
Source file
</body>
</html>
This is an old question but I think in 2022 there are ES6 ways to handle this:
const $node = document.getElementById('output')
const $file = document.getElementById('file')
const processTextByLine = text => {
const arr = text.split(/\r?\n/gm)
arr.map(line => console.log(line))
}
const openFile = event => {
const input = event.target
if (!input) throw new Error('null input')
const [first] = input.files
const reader = new FileReader()
reader.onload = () => {
const text = reader.result
$node.innerText = text
processTextByLine(text)
}
reader.readAsText(first)
}
$file.onchange = openFile
<input id='file' type='file' accept='text/plain'><br>
<div id='output'>
...
</div>
If your file is encoded using UTF-8 then we can make an async call using Blob.text()
const $node = document.getElementById('output')
const $file = document.getElementById('file')
const processTextByLine = text => {
const arr = text.split(/\r?\n/gm)
arr.map(line => console.log(line))
}
const openFile = async event => {
const input = event.target
if (!input) throw new Error('null input')
const [file] = input.files
const text = await file.text()
$node.innerText = text
processTextByLine(text)
}
$file.onchange = openFile
<input id='file' type='file' accept='text/plain'><br>
<div id='output'>
...
</div>
Note:
processTextByLine() function is not needed, it just shows a case if we need to process the file line by line.
I have a question regarding to JavaScript validation. I am validaing the <input type="file"> whenever my scripts runs, it validates but also the action page is called. I want to stop the action page until the validation is complete. Here is my code, any help will be awesome. Regards
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Image Uploading</title>
</head>
<body>
<form name="xx" action="server.php" method="post" enctype="multipart/form-data" onsubmit="Checkfiles(this)">
<input type="file" name="file_uploading" id="filename">
<input type="submit" value="Submit" name="uploadfile">
</form>
<form name="view" method="post">
View your uploaded Images
</form>
</body>
</html>
<script type="text/javascript">
function Checkfiles() {
var fup = document.getElementById('filename');
var fileName = fup.value;
var ext = fileName.substring(fileName.lastIndexOf('.') + 1);
if(ext =="GIF" || ext=="gif") {
return true;
} else {
alert("Upload Gif Images only");
return false;
}
}
</script>
var fname = "the file name here.ext";
var re = /(\.jpg|\.jpeg|\.bmp|\.gif|\.png)$/i;
if (!re.exec(fname)) {
alert("File extension not supported!");
}
File Extension Validation through javascript
function ValidateExtension() {
var allowedFiles = [".doc", ".docx", ".pdf"];
var fileUpload = document.getElementById("fileUpload");
var lblError = document.getElementById("lblError");
var regex = new RegExp("([a-zA-Z0-9\s_\\.\-:])+(" + allowedFiles.join('|') + ")$");
if (!regex.test(fileUpload.value.toLowerCase())) {
lblError.innerHTML = "Please upload files having extensions: <b>" + allowedFiles.join(', ') + "</b> only.";
return false;
}
lblError.innerHTML = "";
return true;
}
onclick event of submit button call this javascript function.
With the help of ID = lblError , print the error message in html section.
You can use the File Api to test for magic number. Maybe take a look at this answer for other ideas about the validation. More reliable than the file extension check.
The return value of the submit handler affects the submission.
onsubmit="return Checkfiles();"
This is basically saying:
form.onsubmit = function () { return Checkfiles(); };
In general, you can use JavaScript some() method for that.
function isImage(icon) {
const ext = ['.jpg', '.jpeg', '.bmp', '.gif', '.png', '.svg'];
return ext.some(el => icon.endsWith(el));
}
const fname = "filename.ext";
if (!isImage(fname)) {
console.log("File extension not supported!");
}
You need to return CheckFiles()
Upload bulk data through excel sheet(.csv)
$("form").submit(function(){
var val = $(this).val().toLowerCase();
var regex = new RegExp("(.*?)\.(csv)$");
if(!(regex.test(val))) {
$(this).val('');
alert('Only csv file can be uploaded');
return false;
}
});
var _URL = window.URL || window.webkitURL;
$("input[type=file]").change(function(e) {
var file;
if ((file = this.files[0])) {
var img = new Image();
img.onload = function () {
// do to on load
};
img.onerror = function () {
alert("valid format " + file.type);
};
img.src = _URL.createObjectURL(file);
}
});
The fileValidation() function contains the complete file type validation code. This JavaScript function needs to call for file extension validation.
HTML
<!-- File input field -->
<input type="file" id="file" onchange="return fileValidation()"/>
<!-- Image preview -->
<div id="imagePreview"></div>
JavaScript
function fileValidation(){
var fileInput = document.getElementById('file');
var filePath = fileInput.value;
var allowedExtensions = /(\.jpg|\.jpeg|\.png|\.gif)$/i;
if(!allowedExtensions.exec(filePath)){
alert('Please upload file having extensions .jpeg/.jpg/.png/.gif only.');
fileInput.value = '';
return false;
}else{
//Image preview
if (fileInput.files && fileInput.files[0]) {
var reader = new FileReader();
reader.onload = function(e) {
document.getElementById('imagePreview').innerHTML = '<img src="'+e.target.result+'"/>';
};
reader.readAsDataURL(fileInput.files[0]);
}
}
}
fileValidation()
> html
<input type="file" id="userfile" name="userfile" value="" class="form-control userfile" required>
> javascript
$(document).on('change', '.userfile', function (e) {
e.preventDefault();
const thisValue = $(this).val().split('.').pop().toLowerCase();
const userFile = [thisValue];
// Allowing file type
const validFile = ['csv', 'xlsx'];
// const intersection = validFile.filter(element => userFile.includes(element));
// if(intersection == ''){
// $(this).val('');
// alert('Please Select ' + validFile + ' file');
// return false;
// }
// Allowing file type
const allowedExtensions = /(\.csv|\.xlsx)$/i;
if (!allowedExtensions.exec($(this).val())) {
$(this).val('');
alert('Please Select ' + validFile + ' file');
return false;
}
});