I am trying to automatically prompt a user to upload a CSV file and then I plan to access the data within, but I am unable to do this. What am I doing wrong? input.name is always undefined and viewing the whole object doesn't provide any relevant details.
The source of this query primarily came from the answer to this question Open file dialog box in JavaScript. I am trying to achieve this purely in javascript, not HTML.
jsfiddle
$(document).ready(function() {
var input = $(document.createElement('input'));
input.attr("type", "file");
input.on('change',function(){
alert(JSON.stringify(input.name, null, 4));
alert(JSON.stringify(input, null, 4));
});
input.trigger('click');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
input is the return value of $(). It is a jQuery object not a DOM object. To access the name property of the underlying DOM object, use the prop method.
input.prop('name')
I finally got it working. Here is the solution
$(document).ready(function() {
var input = $(document.createElement('input'));
input.attr("type", "file");
input.on('change', function() {
var csvFile = input[0].files[0];
var ext = csvFile.name.split(".").pop().toLowerCase();
if (ext != "csv") {
alert('upload csv');
return false;
}
if (csvFile != undefined) {
reader = new FileReader();
reader.onload = function(e) {
var data = $.csv.toObjects(e.target.result);
alert(JSON.stringify(data, null, 4));
$.each(data, function(index, val) {
//do something with each row of data val.ColumnName
});
}
reader.readAsText(csvFile);
}
});
input.trigger('click');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-csv/1.0.21/jquery.csv.js"></script>
Updated method with security implementations in place: 2023-01-24
You just can't use the document ready function but have to force the user to initiate the file open dialog:
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.3/jquery.min.js" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script type="text/javascript">
console.log(jQuery(). jquery);
$("#file-upload").click(function() {
var input = $(document.createElement('input'));
input.attr("type", "file");
input.on('change', function() {
var csvFile = input[0].files[0];
var ext = csvFile.name.split(".").pop().toLowerCase();
if (ext != "csv") {
alert('upload csv');
return false;
}
if (csvFile != undefined) {
reader = new FileReader();
reader.onload = function(e) {
var data = $.csv.toObjects(e.target.result);
alert(JSON.stringify(data, null, 4));
$.each(data, function(index, val) {
//do something with each row of data val.ColumnName
});
}
reader.readAsText(csvFile);
}
});
input.trigger('click');
});
</script>
</head>
<body>
Upload file
</body>
</html>
Related
I am trying to make a very simple webpage that takes an input file and displays the contents in the console. When I try to use it, it sort of works, but is always one step behind. For example,
1) Upload "1.txt" -> Console prints ""
2) Upload "2.txt" -> Console prints contents of "1.txt"
3) Upload "3.txt" -> Console prints contents of "2.txt"
...
function readData(){
var fileholder = document.querySelector('#knotFiles');
var content = 'Empty';
var reader = new FileReader();
reader.onload = function(event){
content = event.target.result;
}
fileholder.addEventListener("input", function(event) {
var files = fileholder.files;
reader.readAsText(files[0]);
console.log(content);
}, false);
return content;
};
readData();
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<link rel="stylesheet" href="" />
<title></title>
</head>
<body>
<div id="container">
<input type="file" id="knotFiles" multiple>
</div>
<script src="knot.js">
</script>
</body>
</html>
I am new to javascript and web development in general, so I apologize if this is a simple question. Thank you!
render.onload is a async function In sort content = event.target.result; will execute at the end so put console.log(content); inside render.onload for latest changes in content data
function readData(){
var fileholder = document.querySelector('#knotFiles');
var content = 'Empty';
var reader = new FileReader();
reader.onload = function(event){
content = event.target.result;
console.log(content);
}
fileholder.addEventListener("input", function(event) {
var files = fileholder.files;
reader.readAsText(files[0]);
}, false);
return content;
};
readData();
The FileReader() loads asynchronously - you are outputting the previous result because the variable content has not been updated yet before the event listener callback fires. Rewrite like this:
var fileholder = document.querySelector('#knotFiles');
fileholder.addEventListener("input", function(event) {
readData();
}, false);
function readData(){
var content = '';
var files = fileholder.files;
var reader = new FileReader();
reader.readAsText(files[0], "UTF-8"); // assumed this encoding
reader.onload = function(event){
content = event.target.result;
console.log(content);
return content;
};
}
Is it possible to use JavaScript to get an image URL into an <input type="file"> ready for submitting? Or to achieve a similar effect? Practically, I have the image at http://example.com/xxx/image.jpg and I'd like to "preload it" into a use registration form so it can be submitted with the form as if it was loaded from the disk using an input field.
The case scenario is user data obtained from an API that I want to use to populate an user registration form where one field is the user's avatar which the API hand over as a URL.
This is not about how to preview an image selected from disk using an input field!
Example using FileReader API. This load the image loaded in the File object in image html object.
<!DOCTYPE html>
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<div>
<input id="btnFile" type="file" accept="image/*" />
</div>
<div>
<img id="img" style="max-width: 100px" />
</div>
<script>
var btnFile = document.getElementById("btnFile");
//Register event on file selected or changed.
addEvents(btnFile, "change", function (event) {
if (event.target.files.length !== 0) {
var file = event.target.files[0];
//Check if the file is IMAGE.
if (file.type.match("image.*")) {
var fl = new FileReader();
//Add event to read the content file.
addEvents(fl, "load", function (evt) {
//alert(evt.target.result);
try {
//CONVERT ARRAY BUFFER TO BASE64 STRING.
var dataURL = evt.target.result;
document.getElementById("img").src = dataURL;
} catch (e) {
alert(e);
}
});
//Read the file as arraybuffer.
fl.readAsDataURL(file);
} else {
alert("Please select a IMAGE FILE");
}
}
});
function addEvents(obj, evtName, func) {
if (obj.addEventListener !== undefined && obj.addEventListener !== null) {
obj.addEventListener(evtName, func, false);
} else if (obj.attachEvent !== undefined && obj.attachEvent !== null) {
obj.attachEvent(evtName, func);
} else {
if (this.getAttribute("on" + evtName) !== undefined) {
obj["on" + evtName] = func;
} else {
obj[evtName] = func;
}
}
}
function removeEvents(obj, evtName, func) {
if (obj.removeEventListener !== undefined && obj.removeEventListener !== null) {
obj.removeEventListener(evtName, func, false);
} else if (obj.detachEvent !== undefined && obj.detachEvent !== null) {
obj.detachEvent(evtName, func);
} else {
if (this.getAttribute("on" + evtName) !== undefined) {
obj["on" + evtName] = null;
} else {
obj[evtName] = null;
}
}
}
</script>
</body>
</html>
It is not possible. As an alternative solution you can use an input[type="url"] and then on submit create the file to upload with JavaScript:
async function getFileFromUrl(url, name, defaultType = 'image/png') {
const response = await fetch(url)
const data = await response.blob()
return new File([data], name, {
type: data.type || defaultType,
})
}
Or instead of using this function you can convert it as base64:
async function getBase64FromUrl(url) {
let reader = new FileReader();
const response = await fetch(url)
const data = await response.blob()
return await new Promise((resolve, reject) => {
reader.onload = () => resolve(reader.result);
reader.onerror = reject;
reader.readAsDataURL(data);
})
}
And upload the base64 string.
The value of an input type="file" is read-only programatically for security reasons, so no, it is not possible.
Reference Link:
https://www.w3schools.com/jsref/prop_fileupload_value.asp
As Jahl said, it can't be done for security reasons, but as an alternative you can have a hidden input value and populate that. Display the image and have an option to submit a different image -- if no other is submitted, use the loaded avatar by default.
I am sending data via ajax to post in mysql. In this context how to inlude image file contents ?
If i use like :
var formData = document.getElementById("img_file");
alert(formData.files[0]);
, i get error . Note : img_file is the id of the file dom.
Any idea about this ?
You can use javascript FileReader for this purpose. Here is a sample code demonstration.
<html>
<body>
<input type="file" id="fileinput" />
<div id="ReadResult"></div>
<script type="text/javascript">
function readSingleFile(evt) {
//Retrieve the first (and only!) File from the FileList object
var f = evt.target.files[0];
if (f) {
var r = new FileReader();
r.onload = function (e) {
var contents = e.target.result;
document.getElementById("ReadResult").innerHTML = contents;
}
r.readAsText(f);
} else {
alert("Failed to load file");
}
}
document.getElementById('fileinput').addEventListener('change', readSingleFile, false);
</script>
</body>
</html>
Find more details here.
i think it may help you.
$('#image').change(function () {
$("#add").attr("disabled", true);
var img = this.files[0];
var reader = new FileReader;
reader.readAsDataURL(img);
reader.onload = function (e) {
var file = new Image;
file.src = e.target.result;
file.onload = function () {
$("#height").text(file.height);
$("#width").text(file.width);
$("#imageprev").attr("src", file.src);
$("#upld").removeAttr("disabled");
}
}
});
I am new to Javascript and IndexedDB. Currently I am writing code for a simple utility which uploads file(s) and stores them in IndexedDB. Then user has the option of either seeing the file names or the contents of the file, which is directly read from stored files in IndexedDB.
Following is my javascript code-
var db;
var display="";
function indexedDOok(){
return "indexedDB" in window;
}
document.addEventListener("DOMContentLoaded", function(){
if(!indexedDOok())
return;
var openRequest = indexedDB.open("fileIndex", 1);
openRequest.onupgradeneeded = function(e){
var thisDB = e.target.result;
if(!thisDB.objectStoreNames.contains("docs")){
thisDB.createObjectStore("docs", {autoIncrement:true});
console.log("Database upgrading....");
}
};
openRequest.onsuccess = function(e){
db = e.target.result;
console.log("Database created");
document.querySelector("#fileSelector").addEventListener("change", handleFileSelection, false);
document.querySelector("#displayButton").addEventListener("click", displayContent, false);
document.querySelector("#getButton").addEventListener("click", getFiles, false);
};
openRequest.onerror = function(e){
console.log(e.target.result);
};
}, false);
function handleFileSelection(e){
console.log("Inside file selection handler...");
var files = e.target.files;
if(!files){
console.log("Files selection failed. Select again");
return;
}//if
try{
var transaction = db.transaction(["docs"],"readwrite");
}catch(ex){
console.log("Exception in opening transaction, "+ex.message);
return;
}//catch
transaction.onerror = function(evt){
console.log("transaction.onerror() fired in handleFileSelection(), error code: "+ (evt.target.error? evt.target.error: evt.target.errorCode));
};
transaction.onabort = function(){
console.log("transaction.onabort() fired in handFileSelection()");
};
transaction.oncomplete = function(){
console.log("transaction.oncomplete() fired in handFileSelection()");
};
try{
var store = transaction.objectStore("docs");
for(var i=0; i<files.length; i++){
file = files[i];
var request = store.put(file);
request.onsuccess = function(){
console.log(files.length);
console.log(file.name+" has been successfully added in table");
};
request.onerror = function(evt){
console.log("Error..."+file.name+" file not added", evt.target.error.name);
};
}
} catch(ex){
console.log("Transaction and/or put() exception in adding file to database...."+ ex.message);
return;
}
};
function getFiles(){
var transaction = db.transaction(["docs"],"readonly");
var cursor = transaction.objectStore("docs").openCursor();
var s ="";
cursor.onsuccess = function(e){
var res = e.target.result;
console.log("Cursor created");
if(res){
s+= "<p>"+res.value.name+"</p>";
res.continue();
}
document.querySelector("#content").innerHTML = s;
};
};
function displayContent(){
var transaction = db.transaction(["docs"],"readonly");
var cursor = transaction.objectStore("docs").openCursor();
document.querySelector("#content").innerHTML = "";
cursor.onsuccess = function(e){
console.log("Inside displayContent() cursor success...");
var res = e.target.result;
if(res){
console.log(res.value.name+ " is loaded");
readerFile(res.value);
res.continue();
}
};
display="";
};
function readerFile(e){
var reader = new FileReader();
reader.readAsText(e);
reader.onload = function(ex){
var rawData = reader.result;
display = document.querySelector("#content");
display.innerHTML = display.innerHTML + "<h2> "+e.name+ "</h2>";
display.innerHTML = display.innerHTML + rawData;
};
}
Following is my index.html
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="files/dbFile.js"></script>
</head>
<body>
<input type="file" id="fileSelector" multiple>
<br><br>
<button id="displayButton">Display Content</button>
<button id="getButton">Display Files</button>
<pre id="content"></pre>
</body>
</html>
It is running successfully in all the browsers. Files are getting uploaded and stored and also getting read and displayed. But only in Chrome it's giving the error "Failed to execute 'put' on 'IDBObjectStore': The object store currently does not support blob values."
Following is the output of Chrome's console, when I try uploading a file-
Database upgrading....
Database created
Inside file selection handler... dbFile.js:38
Transaction and/or put() exception in adding file to database....Failed to execute 'put' on 'IDBObjectStore': The object store currently does not support blob values. dbFile.js:75
transaction.oncomplete() fired in handFileSelection()
Can someone please help me. Why is this happening? I did a lot of research but found nothing helpful
The code below is to read a text file using javascript. it works.
However, I just want to read part of the content.
For example, the content of the file is :"Hello world!"
I just want to display "Hello".
I tried function split(), but it only works on strings. I don't know how to insert it here.
var urls = ["data.txt"];
function loadUrl() {
var urlToLoad = urls[0];
alert("load URL ... " + urlToLoad);
browser.setAttributeNS(xlinkNS, "href", urlToLoad);
}
thank you!!!
I used
jQuery.get('http://localhost/foo.txt', function(data) {
var myvar = data;
});
, and got data from my text file.
Or try this
JQuery provides a method $.get which can capture the data from a URL. So to "read" the html/text document, it needs to be accessible through a URL. Once you fetch the HTML contents you should just be able to wrap that markup as a jQuery wrapped set and search it as normal.
Untested, but the general gist of it...
var HTML_FILE_URL = '/whatever/html/file.html';
$(document).ready(function() {
$.get(HTML_FILE_URL, function(data) {
var fileDom = $(data);
fileDom.find('h2').each(function() {
alert($(this).text());
});
});
});
Try this to read separate words if I understood correctly what you need.
Create a file with the contents "hello world" and browse to it with the example script.
The output is "hello".
<html>
<head>
<input type="file" id="fileinput" />
<script type="text/javascript">
function readSingleFile(evt) {
var f = evt.target.files[0];
if (f) {
var r = new FileReader();
r.onload = function(e) {
var contents = e.target.result;
var ct = r.result;
var words = ct.split(' ');
alert(words[0]);
}
r.readAsText(f);
} else {
alert("Failed to load file");
}
}
document.getElementById('fileinput').addEventListener('change', readSingleFile, false);
</script>
</head>
<body>
</body>
</html>
Reading directly has to be with an ajax request due to the javascript restrictions regarding safety.
This code shoudl perform the requested operation:
<html>
<head>
<input type="file" id="fileinput" />
<script type="text/javascript">
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){
if(xmlhttp.status==200 && xmlhttp.readyState==4){
var words = xmlhttp.responseText.split(' ');
alert(words[0]);
}
}
xmlhttp.open("GET","FileName.txt",true);
xmlhttp.send();
</script>
</head>
<body>
</body>
</html>
Opening a file in javascript with ajax (without using any framework)
var urls = ["data.txt"];
xhrDoc= new XMLHttpRequest();
xhrDoc.open('GET', urls[0] , async)
if (xhrDoc.overrideMimeType)
xhrDoc.overrideMimeType('text/plain; charset=x-user-defined')
xhrDoc.onreadystatechange =function()
{
if (this.readyState == 4)
{
if (this.status == 200)
{
var data= this.response; //Here is a string of the text data
}
}
}
xhrDoc.send() //sending the request