javascript file reader on button click error: undefined refference - javascript

I'm trying to get a local file from a system, I did some searching and came around a way of doing this, when I tried to implement it in my code, I got the error:
Uncaught TypeError: Cannot read property 'type' of undefined
document.getElementById('add-new-cat').addEventListener('click', handleFileSelect, false);
function handleFileSelect(evt) {
var files = evt.target.files;
if(files.type.match('image.*')) {
var reader = new FileReader();
reader.onload = (function(theFile) {
})(files);
var catIMG = reader.readAsBinaryString(files);
alert(catIMG);
}
}
<input type="file" name="cat_path_orig" id="cat-path-orig">
<button class="btn btn-primary" id="add-new-cat">add</button>
I wouldn't know how to trigger the function with the file included, because I know it's looking for a value in the button that's being clicked

The click event object doesn't have a files property. I think you're looking for the files property on the input type="file" object:
document.getElementById('add-new-cat').addEventListener('click', handleFileSelect, false);
function handleFileSelect(evt) {
var files = document.getElementById("cat-path-orig").files; // ****
console.log("files.length: " + files.length);
Array.prototype.forEach.call(files, function(file) {
console.log(file.name + ": " + file.type);
});
}
<input type="file" name="cat_path_orig" id="cat-path-orig">
<button class="btn btn-primary" id="add-new-cat">add</button>
A couple of other notes:
You'll want to look at the type property on each individual file (see the snippet above). In your example, there will be only one (because there's no multiple attribute on the input type="file"), so you could just use files[0] rather than the loop I've used above.
Your use of readAsBinaryString is also incorrect; here's an answer with a correct example.

Related

Read a file in browser in JS [duplicate]

I have this code and for a file to be converted into base64 I have to click on Choose file and then select it. I want to hardcode the file name so it is converted to base64 on page load.
JavaScript:
var handleFileSelect = function(evt) {
var files = evt.target.files;
var file = files[0];
if (files && file) {
var reader = new FileReader();
reader.onload = function(readerEvt) {
var binaryString = readerEvt.target.result;
document.getElementById("base64textarea").value = btoa(binaryString);
};
reader.readAsBinaryString(file);
}
if (window.File && window.FileReader
&& window.FileList && window.Blob) {
document.getElementById('filePicker')
.addEventListener('change', handleFileSelect, false);
} else {
alert('The File APIs are not fully supported in this browser.');
}
};
HTML:
<div>
<div>
<label for="filePicker">Choose or drag a file:</label><br/>
<input type="file" id="filePicker">
</div>
</br>
<div>
<h1>Base64 encoded version</h1>
<textarea id="base64textarea"
placeholder="Base64 will appear here"
cols="50" rows="15">
</textarea>
</div>
</div>
EDIT: Thank you for your answers, they were really helpful.
You simply can't do what you are trying to do. Setting the path for an input element through Javascript is not possible, as a security measure. Please check here: How to resolve the C:\fakepath?
You can launch chromium, chrome browser with --allow-file-access-from-files flag set, use fetch() of XMLHttpRequest() to request file from local filesystem.
fetch("file:///path/to/file")
.then(response => response.arrayBuffer())
.then(ab => {
// do stuff with `ArrayBuffer` representation of file
})
.catch(err => console.log(err));
See also Read local XML with JS
The File API is not good to read local files without user intervention, but the Web API is (of course, within its limitations, like not working in Chromium without explicitly enabling access to local files and whatnot).
So, here it is, in case someone else needs a working example of how to load a local file without user intervention, i.e., without requiring user to push any INPUT button (but still giving the user a means to abort the loading).
Parameters: file name, request type (text, blob etc.), MIME type and a function to be executed after the file is completely loaded. File is loaded in variable X, which is then used to populated an object.
To abort the file reading, just click on the progress bar (also, just an example, not essential for the program to work). Because it is asynchronous, as many files as wanted may be read at the same time (one progress bar is created for each file).
I only created examples for a text file and a video, but it should work with any kind of files.
<html>
<head>
<meta charset="utf-8"/>
<script type="text/javascript">
function LoadFile(FileName,RespType,FileType,RunMe)
{ var AJAXFileReader=new XMLHttpRequest();
// Creates new progress bar.
var ProgressBar=CreateSVGProgBar("ProgressBars");
AJAXFileReader.addEventListener("progress",
function FRProgress(AJAXFREvt)
{ // Calculate progress.
var X=-1;
if (AJAXFREvt.lengthComputable)
X=Math.trunc(AJAXFREvt.loaded/AJAXFREvt.total*100);
ShowProgressBar(ProgressBar,FileName,X);
});
AJAXFileReader.addEventListener("error",function FRFailed()
{ // This will be executed if an error occurs.
console.log("Error:",this.status);
});
AJAXFileReader.addEventListener("timeout",function FRTimeOut()
{ // This will be executed if the reading times out.
console.log("File reading timed out!");
});
AJAXFileReader.addEventListener("abort",
function FRCancel()
{ // This will confirm reading was aborted.
console.log("File reading cancelled by user!");
});
ProgressBar.addEventListener("click",
function KillMe()
{ // Adds an abort command to the object.
console.log(AJAXFileReader.readyState);
if (AJAXFileReader.readyState!=4)
{ console.log("Aborting file reading...");
AJAXFileReader.abort();
}
ProgressBar.removeEventListener("click",KillMe);
},
false);
AJAXFileReader.addEventListener("load",
function Finished()
{ // When reading is finished, send data to external function.
if ((this.readyState==4)&&(this.status==200))
{ ShowProgressBar(ProgressBar,FileName,100);
RunMe(this.response);
//ProgressBar.click();
}
},
false);
AJAXFileReader.open("GET",FileName,true);
AJAXFileReader.overrideMimeType(FileType);
AJAXFileReader.responseType=RespType;
AJAXFileReader.timeout=10000; // Setting time-out to 10 s.
AJAXFileReader.send();
}
function CreateSVGProgBar(AnchorId)
{ // Creates new SVG progress bar.
var Parent=document.getElementById(AnchorId);
var NewSVG=document.createElementNS("http://www.w3.org/2000/svg","svg");
NewSVG.setAttribute("viewBox","0 0 102 22");
NewSVG.setAttribute("width","102");
NewSVG.setAttribute("height","22");
Parent.appendChild(NewSVG);
return NewSVG;
}
function ShowProgressBar(E,N,X)
{ // Show progress bar.
var P=X<0?"???":X+"%";
E.innerHTML="<text x=\"50\" y=\"16\" font-size=\"12\" fill=\"black\" stroke=\"black\" text-anchor=\"middle\">"+N+"</text><rect x=\"1\" y=\"1\" width=\""+X+"\" height=\"20\" fill=\""+(X<100?"#FF0000":"#0000FF")+"\" stroke=\"none\"/><rect x=\"1\" y=\"1\" width=\"100\" height=\"20\" fill=\"none\" stroke=\"black\" stroke-width=\"1\"/><text x=\""+X/2+"\" y=\"16\" font-size=\"12\" fill=\"black\" stroke=\"black\" text-anchor=\"middle\">"+P+"</text>";
}
function TracerOn(X)
{ // This will be executed after the file is completely loaded.
document.getElementById("Tron").innerHTML=X;
}
function PlayIt(X)
{ // This will be executed after the file is completely loaded.
var blob_uri=URL.createObjectURL(X);
document.getElementById("MagicalBox").appendChild(document.createElement("source")).src=blob_uri;
}
function Startup()
{ // Run after the Page is loaded.
LoadFile("example.txt","text","text/plain;charset=utf-8",TracerOn);
LoadFile("video.mp4","blob","video/mp4",PlayIt);
}
</script>
</head>
<body onload="Startup()">
<div id="ProgressBars"></div>
<div id="Tron">Text...</div>
<video id="MagicalBox" width="400" controls>Video...</video>
</body>
</html>

What does all my images start with the same sequence?

Continuing my experiments and my last question (Solved BTW, THANKS!!) i realized that all the images that i upload start with the same sequence:
/9j/4AAQSkZJRgABAQAAAQABAAD/
Does anyone knows what is that? my first impression was that it should be somekind of CRC but it has to change with every upladed file
My code is:
<button type="button" class="btn btn-primary" id="bid_uploadPicture">Subir Imagen</button>
<input type="file" id="file" accept='image/*' style="display:none;" />
jQuery(function ($) {
$("#bid_uploadPicture").click(function () {
event.preventDefault();
document.getElementById("file").click();
});
$("#file").change(function () {
var fr = new FileReader();
fr.onload = function (e) {
data = new Uint8Array(e.target.result)
console.log(e.target.result);
}
//fr.readAsArrayBuffer(this.files[0]);
fr.readAsDataURL(this.files[0]);
});
});
I just give with the answer, im posting here in case some one else has the same interest
It turns out that this sequence is the JPG signature and the format structure of the uploaded picture as explained in this wikipedia article:
https://en.wikipedia.org/wiki/JPEG_File_Interchange_Format
Regards!!!

Read local file in javascript [duplicate]

I have this code and for a file to be converted into base64 I have to click on Choose file and then select it. I want to hardcode the file name so it is converted to base64 on page load.
JavaScript:
var handleFileSelect = function(evt) {
var files = evt.target.files;
var file = files[0];
if (files && file) {
var reader = new FileReader();
reader.onload = function(readerEvt) {
var binaryString = readerEvt.target.result;
document.getElementById("base64textarea").value = btoa(binaryString);
};
reader.readAsBinaryString(file);
}
if (window.File && window.FileReader
&& window.FileList && window.Blob) {
document.getElementById('filePicker')
.addEventListener('change', handleFileSelect, false);
} else {
alert('The File APIs are not fully supported in this browser.');
}
};
HTML:
<div>
<div>
<label for="filePicker">Choose or drag a file:</label><br/>
<input type="file" id="filePicker">
</div>
</br>
<div>
<h1>Base64 encoded version</h1>
<textarea id="base64textarea"
placeholder="Base64 will appear here"
cols="50" rows="15">
</textarea>
</div>
</div>
EDIT: Thank you for your answers, they were really helpful.
You simply can't do what you are trying to do. Setting the path for an input element through Javascript is not possible, as a security measure. Please check here: How to resolve the C:\fakepath?
You can launch chromium, chrome browser with --allow-file-access-from-files flag set, use fetch() of XMLHttpRequest() to request file from local filesystem.
fetch("file:///path/to/file")
.then(response => response.arrayBuffer())
.then(ab => {
// do stuff with `ArrayBuffer` representation of file
})
.catch(err => console.log(err));
See also Read local XML with JS
The File API is not good to read local files without user intervention, but the Web API is (of course, within its limitations, like not working in Chromium without explicitly enabling access to local files and whatnot).
So, here it is, in case someone else needs a working example of how to load a local file without user intervention, i.e., without requiring user to push any INPUT button (but still giving the user a means to abort the loading).
Parameters: file name, request type (text, blob etc.), MIME type and a function to be executed after the file is completely loaded. File is loaded in variable X, which is then used to populated an object.
To abort the file reading, just click on the progress bar (also, just an example, not essential for the program to work). Because it is asynchronous, as many files as wanted may be read at the same time (one progress bar is created for each file).
I only created examples for a text file and a video, but it should work with any kind of files.
<html>
<head>
<meta charset="utf-8"/>
<script type="text/javascript">
function LoadFile(FileName,RespType,FileType,RunMe)
{ var AJAXFileReader=new XMLHttpRequest();
// Creates new progress bar.
var ProgressBar=CreateSVGProgBar("ProgressBars");
AJAXFileReader.addEventListener("progress",
function FRProgress(AJAXFREvt)
{ // Calculate progress.
var X=-1;
if (AJAXFREvt.lengthComputable)
X=Math.trunc(AJAXFREvt.loaded/AJAXFREvt.total*100);
ShowProgressBar(ProgressBar,FileName,X);
});
AJAXFileReader.addEventListener("error",function FRFailed()
{ // This will be executed if an error occurs.
console.log("Error:",this.status);
});
AJAXFileReader.addEventListener("timeout",function FRTimeOut()
{ // This will be executed if the reading times out.
console.log("File reading timed out!");
});
AJAXFileReader.addEventListener("abort",
function FRCancel()
{ // This will confirm reading was aborted.
console.log("File reading cancelled by user!");
});
ProgressBar.addEventListener("click",
function KillMe()
{ // Adds an abort command to the object.
console.log(AJAXFileReader.readyState);
if (AJAXFileReader.readyState!=4)
{ console.log("Aborting file reading...");
AJAXFileReader.abort();
}
ProgressBar.removeEventListener("click",KillMe);
},
false);
AJAXFileReader.addEventListener("load",
function Finished()
{ // When reading is finished, send data to external function.
if ((this.readyState==4)&&(this.status==200))
{ ShowProgressBar(ProgressBar,FileName,100);
RunMe(this.response);
//ProgressBar.click();
}
},
false);
AJAXFileReader.open("GET",FileName,true);
AJAXFileReader.overrideMimeType(FileType);
AJAXFileReader.responseType=RespType;
AJAXFileReader.timeout=10000; // Setting time-out to 10 s.
AJAXFileReader.send();
}
function CreateSVGProgBar(AnchorId)
{ // Creates new SVG progress bar.
var Parent=document.getElementById(AnchorId);
var NewSVG=document.createElementNS("http://www.w3.org/2000/svg","svg");
NewSVG.setAttribute("viewBox","0 0 102 22");
NewSVG.setAttribute("width","102");
NewSVG.setAttribute("height","22");
Parent.appendChild(NewSVG);
return NewSVG;
}
function ShowProgressBar(E,N,X)
{ // Show progress bar.
var P=X<0?"???":X+"%";
E.innerHTML="<text x=\"50\" y=\"16\" font-size=\"12\" fill=\"black\" stroke=\"black\" text-anchor=\"middle\">"+N+"</text><rect x=\"1\" y=\"1\" width=\""+X+"\" height=\"20\" fill=\""+(X<100?"#FF0000":"#0000FF")+"\" stroke=\"none\"/><rect x=\"1\" y=\"1\" width=\"100\" height=\"20\" fill=\"none\" stroke=\"black\" stroke-width=\"1\"/><text x=\""+X/2+"\" y=\"16\" font-size=\"12\" fill=\"black\" stroke=\"black\" text-anchor=\"middle\">"+P+"</text>";
}
function TracerOn(X)
{ // This will be executed after the file is completely loaded.
document.getElementById("Tron").innerHTML=X;
}
function PlayIt(X)
{ // This will be executed after the file is completely loaded.
var blob_uri=URL.createObjectURL(X);
document.getElementById("MagicalBox").appendChild(document.createElement("source")).src=blob_uri;
}
function Startup()
{ // Run after the Page is loaded.
LoadFile("example.txt","text","text/plain;charset=utf-8",TracerOn);
LoadFile("video.mp4","blob","video/mp4",PlayIt);
}
</script>
</head>
<body onload="Startup()">
<div id="ProgressBars"></div>
<div id="Tron">Text...</div>
<video id="MagicalBox" width="400" controls>Video...</video>
</body>
</html>

Read an input tag into a javascript string

I'm trying to read an input type="file" tag into a javascript string. I know this should be simple but I simply cannot get my code to work. The file is plain .html. Here's what I have
<h3>Select location of html file.</h3>
<form onSubmit="submitButtonPressed()">
<input type="file" id="classList" />
<input type="submit" />
</form>
<script>
var reader = new FileReader();
var htmlFile = document.getElementById("classList").files[0]; //read the file selected with the <input> tag
reader.readAsText(htmlFile);
var htmlText = reader.result; //and create a string with the contents
function submitButtonPressed() {
var lengthOfText = htmlText.length;
alert("It is " + lengthOfText + " characters long");
}
</script>
I'm just trying to create a string that contains the contents of the .html file selected by the input tag. I can't figure out why htmlText doesn't contain the contents of the .html file, could someone explain what I'm doing wrong?
this is the right answer for you :
HTML5 File API: How to see the result of readAsText()
reader.onload = function(e) {
// e.target.result should contain the text
};
reader.readAsText(file);
so i guess you will have to check on pressing the button if the file was loaded or not , maybe it is still in progress , or encountered an error

Passing path to uploaded file from HTML5 drag & drop to input field

I'm working on an application (in Node.js, which is irrelevant for this case) which allows the user to upload an image. It works fine using a form with an input (type="file") field.
However, what I want is to be able to upload an image using HTML5 drag and drop instead. As far as i've come it's possible to drag an image to the client, and the image thumbnail is displayed in a div. However I really need some help with getting the file upload working.
The thing is that I want to use the form that i'm using right now, and (somehow) pass the file's path to the input field, i.e. the flow will work exactly as it do now, but instead of choosing a file by browsing it I want to attach it to the input field by drag and drop.
In the js code below for drag and drop the file that was dragged to the client is stored in the variable "file", and i'm able to use "file.name", "file.type" and "file.size" exactly the same way as it works since before with the form. However, I can't access the files "path" (file.path) which makes it impossible to access the file server side for uploading the same way as I do it since before.
The question is, is it possible to pass the file object to the input field after the file has been dragged to the client, so that I can click on "submit" and upload the file? If so, how could this be done?
Thanks in advance!
the dropbox as well as the form i'm using for file uploads:
<div id='upload'>
<article>
<div id='holder'>
<p id='status'>File API and FileReader API not supported</p>
</div>
</article>
<form method='post' enctype='multipart/form-data' action='/file-upload'>
<p>
<input type='file' name='thumbnail'>
</p>
<p>
<input type='submit'>
</p>
</form>
</div>
the code for drag and drop:
uploadImage: function(){
var holder = document.getElementById('holder'),
state = document.getElementById('status');
if (typeof window.FileReader === 'undefined') {
state.className = 'fail';
} else {
state.className = 'success';
state.innerHTML = 'File API & FileReader available';
}
holder.ondragover = function () { this.className = 'hover'; return false; };
holder.ondragend = function () { this.className = ''; return false; };
holder.ondrop = function (e) {
this.className = '';
e.preventDefault();
var file = e.dataTransfer.files[0],
reader = new FileReader();
reader.onload = function (event) {
holder.style.background = 'url(' + event.target.result + ') no-repeat center';
};
reader.readAsDataURL(file);
return false;
};
},
You cannot use the file input to add the file data.
Nevertheless, what you can do (among other technics) is to use the base64 (natively available through the reader.onload event as event.target.result, when using readAsDataURL method) encoded data and put it into an hidden field :
html
<article>
<div id='holder'>
<p id='status'>File API and FileReader API not supported</p>
</div>
</article>
<form method='post' enctype='multipart/form-data' action='/file-upload'>
<input type='file' name='thumbnail' />
<input type='hidden' name='base64data' />
<input type='submit' formenctype='application/x-www-form-urlencoded' />
</form>
js
reader = new FileReader();
reader.onload = function (event) {
document.getElementById('base64data').setAttribute('value', event.target.result);
};
reader.readAsDataURL(file);
From the server side you'll be able to get the base64 encoded data from the file, just decode it and use it as you want.
While submitting the form, you could also change the "enctype" attribute (done through the formenctype attribute) and remove the basic html file input, since the data will be post in a text field.
It is impossible to know the path of the field for security purposes. With drag and drop you must have it upload independently of the main form. Look here for an example: http://www.sitepoint.com/html5-file-drag-and-drop/
I find that the hidden field set in reader.onload (see answer by #challet) is not set when acccessed in code behind. I am using asp.net and a WebForms project. To access the hidden fields I have to prepend MainContent_ to the field names. aspx code is below
<asp:Content ID="Content3" ContentPlaceHolderID="MainContent" runat="server">
...
<script type="text/javascript">
function dropHandler(ev) {
alert("File(s) dropped");
// Prevent default behavior (Prevent file from being opened)
ev.preventDefault();
//alert("Default prevented");
if (ev.dataTransfer.items) {
if (ev.dataTransfer.items.length > 1) {
alert("Only single files can be dragged and dropped into Caption Pro Web");
return;
}
// If dropped items aren't files, reject them
if (ev.dataTransfer.items[0].kind === 'file') {
var file = ev.dataTransfer.items[0].getAsFile();
document.getElementById("MainContent_DroppedFileName").value = ev.dataTransfer.items[0].name
reader = new FileReader();
reader.onload = function (event) {
document.getElementById('MainContent_DroppedFileContent').value = event.target.result;
};
reader.readAsDataURL(ev.dataTransfer.items[0]);
}
} else {
// Use DataTransfer interface to access the file(s)
if (ev.dataTransfer.files.length > 1) {
alert("Only single files can be dragged and dropped into Caption Pro Web");
return;
}
document.getElementById("MainContent_DroppedFileName").value = ev.dataTransfer.files[0].name
document.getElementById("MainContent_DroppedFileContent").value = "Test";
reader = new FileReader();
reader.onload = function (event) {
document.getElementById("MainContent_DroppedFileContent").value = event.target.result;
};
reader.readAsDataURL(ev.dataTransfer.files[0]);
}
document.getElementById('<%=btnDrop.ClientID %>').click();
}
</script>
...
<div id="drop_zone" ondrop="dropHandler(event);" ondragover="dragOverHandler(event);">
<p>Drag image to this Drop Zone ...</p>
</div>
<asp:HiddenField ID="DroppedFileName" runat="server" />
<asp:HiddenField ID="DroppedFileContent" runat="server" />
...
</asp:Content>
I access the hidden fields from c# as shown below
protected void btnDrop_Click(object sender, EventArgs e)
{
string FileName = DroppedFileName.Value;
string FileContent = DroppedFileContent.Value;
}
If I use Internet Explorer as the target browser (not running VS as Admin as this disables drag/drop!) and set a breakpoint in the reader.onload() function the hidden field DroppedFileContent contains the encoded file content, but when I try to access it from btnDrop_Click it only contains "Test" as set before reader.onload() and does not contain the encoded file content. The field DroppedFileNam.Value is as set in the Javascript.

Categories

Resources