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>
Related
txt file maybe utf8/GB2312,.... but if upload to my server, i got ascii only. how to detect file encoding, so i can set in readAsText()?
$("#fileinput").change(function(evt){
if (!checkSupport())return;
var f = evt.target.files[0];
if (!f) return;
var r = new FileReader();
r.onload = function(evt){ //file loaded successfuly
g_fname=f.name;
g_contents = evt.target.result;
curpage.val(0);
read_article();
}
r.readAsText(f,'GB2312');
});
As of 2021 I think the easiest solution is to use detect-file-encoding-and-language!
You can simply load it via the <script> tag:
<script src="https://unpkg.com/detect-file-encoding-and-language/umd/language-encoding.min.js"></script>
From the documentation:
// index.html
<body>
<input type="file" id="my-input-field" />
<script src="https://unpkg.com/detect-file-encoding-and-language/umd/language-encoding.min.js"></script>
<script src="app.js"></script>
</body>
// app.js
document.getElementById("my-input-field").addEventListener("change", inputHandler);
function inputHandler(e) {
const file = e.target.files[0];
languageEncoding(file).then(fileInfo => console.log(fileInfo));
// Possible result: { language: english, encoding: UTF-8, confidence: { language: 0.97, encoding: 1 } }
}
I know this is an old post, but since it is unanswered, I'd like to throw this out there to anyone who might be interested:
You should check out this library encoding.js
They also have a working demo. I would suggest you first try it out with the files that you'll typically work with to see if it detects the encoding correctly and then use the library in your project.
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>
I've got a text file and want to do some find and replace operations to it inside the browser. Unfortunately my coding experience is just really elementary and complete tutorials about building web apps are far too much input at the moment.
Basically I want to upload the file into the browser, then let javascript do the find-and-replace-thing and finally want to download the changed file again.
I've already read about the HTML5 File API and was actually able to load the text file into the browser. But that is where I'm getting lost. In order to split problems up into smaller ones I thought a good next step would be to download the uploaded file again and finally learn how to put the find-and-replace action in between. But I really don't know how to go further and would appreciate any help.
Thanks so far. Benny
document.getElementById('input-file')
.addEventListener('change', getFile)
function getFile(event) {
const input = event.target
if ('files' in input && input.files.length > 0) {
placeFileContent(
document.getElementById('content-target'),
input.files[0])
}
}
function placeFileContent(target, file) {
readFileContent(file).then(content => {
target.value = content
}).catch(error => console.log(error))
}
function readFileContent(file) {
const reader = new FileReader()
return new Promise((resolve, reject) => {
reader.onload = event => resolve(event.target.result)
reader.onerror = error => reject(error)
reader.readAsText(file, "windows-1252")
})
}
<html>
<head>
<meta content="text/html; charset=ANSI" http-equiv="content-type">
<title>Text file manipulator</title>
</head>
<body>
<h1>Text file manipulator</h1>
<p>
<input type="file" id="input-file">
</p>
<p>
<textarea id="content-target" style="width:440px;height:400px;"></textarea>
</p>
</body>
</html>
screenshot of text file uploader
You can add a button and call a function in your JavaScript. Something like
<button onclick="downloadText()">Download</button>
Being the function
function downloadText(){
var content = document.getElementById('content-target').value;
var dl = document.createElement('a');
dl.setAttribute('href', 'data:text/csv;charset=utf-8,' +
encodeURIComponent(content));
dl.setAttribute('download', 'text.txt');
dl.click();
}
Inside the function you should be able to do all the modifications you want. If you give more details, I can help you with the replace section of it, but it should be something like the following:
content.replace(regex, substitute);
More information here
Working CodePen
You can use javascript FileReader API to display a preview of an image which is provided from a file input field.
This comes in very useful in the sense that you don't have to use server side php and ajax to display the image.
My question though is this:
Is there any limit to the size of the image file being used? Like if a user was to select an image that is 20MB, would the filereader be able to handle it? And would the machines memory potentially become max-ed out?
I'm testing just locally on my machine at the moment. I attempted to load a bmp file (53MB!), which took about 15 seconds to process and display on the page.
Other files at 1/2MB generally display instantaneously.
It's probably not required, but here is my HTML file: (FYI: this code works well in supported browsers)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>Dropzone File Upload</title>
</head>
<body>
<img id="uploadPreview" src="default.png" style="width: 100px; height: 100px;" />
<input id="uploadImage" type="file" name="myPhoto" onchange="PreviewImage();" />
<p id="uploadProgress"> </p>
<script type="text/javascript">
function PreviewImage() {
var avatar_image = document.getElementById("uploadImage");
var avatar_preview = document.getElementById("uploadPreview");
var avatar_progress = document.getElementById("uploadProgress");
if ( window.FileReader ) { //if supports filereader
var imgReader = new FileReader();
imgReader.readAsDataURL(avatar_image.files[0]); //read from file input
imgReader.onloadstart = function(e) {
avatar_progress.innerHTML = "Starting to Load";
}
imgReader.onload = function (imgReaderEvent) {
//if file is image
if (
avatar_image.files[0].type == 'image/jpg' ||
avatar_image.files[0].type == 'image/jpeg' ||
avatar_image.files[0].type == 'image/png' ||
avatar_image.files[0].type == 'image/gif' ||
avatar_image.files[0].type == 'image/bmp'
) {
avatar_preview.src = imgReaderEvent.target.result;
}
else {
avatar_preview.src = 'filetype.png';
}
}
imgReader.onloadend = function(e) {
avatar_progress.innerHTML = "Loaded!";
}
}
/* For no support, use ActiveX instead */
else {
document.getElementById("uploadPreview").src = "nosupport.png";
}
};
</script>
</body>
</html>
It seems in Chrome 45 the limit is 261 MB.
Unfortunately there is no error (FileReader.error == null) when the size is above that limit, the result is just an empty string.
It appears there is no limitation on the filesize. I did the same thing as you in the past and noticed that the time before display is due to the storage in ram/browser. So the delay will depend on the user's computer. If you have to deal with a lot of big images (> 10MB) you can put a gif loader during the loading.
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.