So I got this script that is supposed to output the file contents of an uploaded file in base64 encoding, the problem is that it also outputs something like data:image/jpeg;base64, at the beginning of the encoded output. What do I need to do so this script just outputs the encoded file contents of the uploaded file and not data:image/jpeg;base64, etc?
<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 PreviewImage() {
var oFReader = new FileReader();
oFReader.readAsDataURL(document.getElementById("uploadImage").files[0]);
oFReader.onload = function (oFREvent) {
var sizef = document.getElementById('uploadImage').files[0].size;
document.getElementById("uploadPreview").src = oFREvent.target.result;
document.getElementById("uploadImageValue").value = oFREvent.target.result;
};
};
jQuery(document).ready(function(){
$('#viewSource').click(function ()
{
var imgUrl = $('#uploadImageValue').val();
document.write(imgUrl);
});
});
</script>
<div>
<input type="hidden" id="uploadImageValue" name="uploadImageValue" value="" />
<img id="uploadPreview" style="width: 150px; height: 150px;" /><br />
<input id="uploadImage" style="width:120px" type="file" size="10" name="myPhoto" onchange="PreviewImage();" />
</div>
Source file
</body>
change code to
document.write(imgUrl.split(',').pop());
^^^^^^^^^^^^^^^^^
or
var imgUrl = $('#uploadImageValue').val().split(',').pop();
^^^^^^^^^^^^^^^^^
Related
I was trying to pass user inputted data in HTML form to csv file on local drive.
But seems some error in it.
I have tried below code even that is copied from other sources.
<html>
<head>
<script language="javascript">
function WriteToFile(passForm) {
var fso = new ActiveXObject("Scripting.FileSystemObject");
var fileLoc = "C:\\sample.txt";
var file = OpenTextFile(fileLoc,2,true,0);
file.write("File handling in Javascript");
file.Close();
alert('File created successfully at location: ' + fileLoc);
}
</script>
</head>
<body>
<p>create a csv file with following details -</p>
<form>
Type your first name: <input type="text" name="FirstName" size="20"><br>
Type your last name: <input type="text" name="LastName" size="20"><br>
<input type="button" value="submit" onclick="WriteToFile(this.form)">
</form>
</body>
</html>
</br></br></html>
CSV file is not getting created and cant get any error in HTML.
You were not using the variable fso to call OpenTextFile, you should also keep in mind that IE has permissions to write in the path
This should work for you:
<html>
<head>
<script language="javascript">
function WriteToFile(passForm) {
var fso = new ActiveXObject("Scripting.FileSystemObject");
var fileLoc = "C:\\Users\\yourUser\\sample.csv";
var file = fso.OpenTextFile(fileLoc,2,true,0);
file.write("File handling in Javascript");
file.Close();
alert('File created successfully at location: ' + fileLoc);
}
</script>
</head>
<body>
<p>create a csv file with following details -</p>
<form>
Type your first name: <input type="text" name="FirstName" size="20"><br>
Type your last name: <input type="text" name="LastName" size="20"><br>
<input type="button" value="submit" onclick="WriteToFile(this.form)">
</form>
</body>
</html>
You can also use this solution that works for several browsers:
<html>
<head>
<script language="javascript">
function downloadCSV(form) {
const content = 'Write your csv content here!!';
const mimeType = 'text/csv;encoding:utf-8';
const fileName = 'download.csv';
const a = document.createElement('a');
if (navigator.msSaveBlob) { // IE10
navigator.msSaveBlob(new Blob([content], {
type: mimeType
}), fileName);
} else if (URL && 'download' in a) { //html5 A[download]
a.href = URL.createObjectURL(new Blob([content], {
type: mimeType
}));
a.setAttribute('download', fileName);
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
} else {
location.href = 'data:application/octet-stream,' + encodeURIComponent(content); // only this mime type is supported
}
}
</script>
</head>
<body>
<p>create a csv file with following details -</p>
<form>
Type your first name: <input type="text" name="FirstName" size="20"><br>
Type your last name: <input type="text" name="LastName" size="20"><br>
<input type="button" value="submit" onclick="downloadCSV(this.form)">
</form>
</body>
</html>
I want to use a different button to upload files to a form. Therefore, i hide the standard upload file button. However, i do want to display the filename when a user uploads a file.
Using wordpress contact form 7, i already tried putting a JS function on the label, but that doesnt work.
<label for="fileInput" class="custom-file-upload" onclick="displayfilename()">Choose file</label>
<input id="fileInput" name="fileInput" type="file" />
<span class="fileuploadspan">No file selected</span>
<script>
function displayfilename()
$('#fileInput').change(function(){
var filename = $(this).val().split('\\').pop();
});
</script>
The filename should be displayed next to the label.
You can use Event.target along with triggering the change event.
Please Note: You also have syntax error in your code (missing the {.......} part of the function displayfilename).
$('#fileInput').change(function(e){
var filename = e.target.files[0].name;
console.log(filename);
});
function displayfilename() {
$('#fileInput').trigger('change');
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label for="fileInput" class="custom-file-upload" >Choose file</label>
<input id="fileInput" name="fileInput" type="file" />
<span class="fileuploadspan">No file selected</span>
OR: You can also use this object:
$('#fileInput').change(function(){
var filename = $(this)[0].files[0].name;
console.log(filename);
});
function displayfilename() {
$('#fileInput').trigger('change');
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label for="fileInput" class="custom-file-upload" >Choose file</label>
<input id="fileInput" name="fileInput" type="file" />
<span class="fileuploadspan">No file selected</span>
$('#fileInput').change(function(e){
var filename = e.target.files[0].name;
console.log(filename);
});
function displayfilename() {
$('#fileInput').trigger('change');
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label for="fileInput" class="custom-file-upload" >Choose file</label>
<input id="fileInput" name="fileInput" type="file" />
<span class="fileuploadspan">No file selected</span>
You can access the file name in this way:
<label for="fileInput" class="custom-file-upload" onclick="displayfilename()">Choose file</label>
<input id="fileInput" name="fileInput" type="file" />
<span class="fileuploadspan">No file selected</span>
<script>
function displayfilename()
$('#fileInput').change(function(e) {
var fileName = e.target.files[0].name;
alert('The file "' + fileName + '" has been selected.');
});
</script>
Here's a custom <button> and a custom filename <span>:
$('.choosefile').click(function () {
$('#fileInput').click();
});
$('#fileInput').change(function(e) {
var filename = this.files[0].name;
$('.fileuploadspan').text(filename);
});
input[type=file] {
display: none
}
.choosefile, .fileuploadspan {
font-family: "Comic Sans MS"
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label for="fileInput" class="custom-file-upload">Choose file</label>
<button class="choosefile">Browse...</button>
<input id="fileInput" name="fileInput" type="file" />
<span class="fileuploadspan">No file selected</span>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<label for="fileInput" class="custom-file-upload">Choose file
<input id="fileInput" name="fileInput" type="file" onchange="uploadPreview(this)" style="display:none"/>
</label><br>
<span class="fileuploadspan">No file selected</span>
</body>
</html>
js
uploadPreview = function (fileInput) {
var files = fileInput.files;
for (var i = 0; i < files.length; i++) {
var file = files[i];
var imageType = /image.*/;
if (!file.type.match(imageType)) {
continue;
}
var reader = new FileReader();
reader.onload = function (e) {
var filename = file.name;
filename = filename.replace('.jpg', '');
filename = filename.replace('.jpeg', '');
filename = filename.replace('.png', '');
filename = filename.replace('.gif', '');
filename = filename.replace('.bmp', '');
$('.fileuploadspan').text(filename);
return;
};
reader.readAsDataURL(file);
}
}
I want to be able to preview a multiple images before it is uploaded, I found solution here that explane how to do that but for just single image.
I trying this :
function readURL(input)
{
if (input.files && input.files[0])
{
for (var i = 0, f; f = files[i]; i++) {
var reader = new FileReader();
reader.onload = function (e) {
$('#blah')
.attr('src', e.target.result)
.width(200)
.height(150);
};
reader.readAsDataURL(f);
}
}
}
Also, change the input to multiple
<input type='file' multiple onchange="readURL(this);" />
<img id="blah" src="#" alt="your image" />
Unfortunately, not working !
How can I do this with multiple images?
With luck this will help you solve the issue 0 seems to work ok for me in test
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8' />
<title>multiple files preview</title>
</head>
<body>
<form method='post' enctype='multipart/form-data'>
<input type='file' name='images[]' multiple />
<input type='submit' />
<output></output>
</form>
<script>
let out=document.querySelector('output');
let oFile=document.querySelector('form > input[type="file"]');
oFile.addEventListener('change', function(e){
let oFiles=this.files;
let oReader;
for( i=0; i < oFiles.length; i++ ){
oReader = new FileReader();
oReader.addEventListener( 'load', e=>{
let img=new Image();
img.src=e.target.result;
out.appendChild( img )
});
oReader.readAsDataURL( oFiles[i] )
}
});
</script>
</body>
</html>
I create script for show image until upload , how i use 5 input files for upload , the script must let show one image , or preview image for each input file
The Script :
<script>
function handleFileSelect(evt,ids) {
var files = evt.target.files;
var f = files[0];
var reader = new FileReader();
reader.onload = (function(theFile) {
return function(e) {
document.getElementById('list'+ids).innerHTML = ['<img src="', e.target.result,'" title="', theFile.name, '" width="50"/>'].join('');
///alert("ok"+ids);
};
})(f);
reader.readAsDataURL(f);
}
</script>
HTML CODE
<input type="file" id="files2" />
<output id="list2"></output>
CALLING SCRIPT FOR THIS INPUT FILE ID
<script>
document.getElementById('files2').addEventListener('change', function(){handleFileSelect('','2');},false);
</script>
As you can see i try send vars from handleFileSelect('','2') , but don´t works never and i think the code it´s well , but sure i forget something , i hope here can help me in this issue , thank´s community
The Best Regards
Try this code
$(function () {
var _URL = window.URL || window.webkitURL;
$(".UploadImage").on("change", function () {
var preview = $(this).attr("data-img");
var file, img;
if ((file = this.files[0])) {
img = new Image();
img.onload = function () {
document.getElementById(preview).src = _URL.createObjectURL(file);
};
img.src = _URL.createObjectURL(file);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<input type="file" data-img="preview1" class="UploadImage" />
<img src="" id="preview1"/>
</div>
<div>
<input type="file" data-img="preview2" class="UploadImage" />
<img src="" id="preview2"/>
</div>
<div>
<input type="file" data-img="preview3" class="UploadImage" />
<img src="" id="preview3"/>
</div>
<div>
<input type="file" data-img="preview4" class="UploadImage" />
<img src="" id="preview4"/>
</div>
It's better if you use CreateObjectURL instead (saves more memory/cpu) it's also faster
var wrapper = document.getElementById('files')
var URL = window.URL || window.webkitURL;
wrapper.addEventListener('change', function(evt){
var input = evt.target
if (input.matches('input[type="file"]') && (input.files || [])[0]) {
var img = new Image
img.width = 50
img.onload = function() {
var output = document.getElementById(input.dataset.for)
output.appendChild(this)
}
img.onerror = function(){
console.log("You uploaded something that is not an image")
}
img.src = URL.createObjectURL(input.files[0])
}
})
output {
display: block;
}
<div id="files">
<!-- Recomend adding accept attribute so you only get images -->
<!-- just made one example -->
<input type="file" data-for="list1" accept="image/*">
<output id="list1"></output>
<input type="file" data-for="list2">
<output id="list2"></output>
<input type="file" data-for="list3">
<output id="list3"></output>
<input type="file" data-for="list4">
<output id="list4"></output>
</div>
Is it possible to save textinput (locally) from a form to a textfile, and then open that document to use it later on?
Just using HTML, javascript and jQuery. No databases or php.
/W
It's possible to save only if the user allow it to be saved just like a download and he must open it manually, the only issue is to suggest a name, my sample code will suggest a name only for Google Chome and only if you use a link instead of button because of the download attribute.
You will only need a base64 encode library and JQuery to easy things.
// This will generate the text file content based on the form data
function buildData(){
var txtData = "Name: "+$("#nameField").val()+
"\r\nLast Name: "+$("#lastNameField").val()+
"\r\nGender: "+($("#genderMale").is(":checked")?"Male":"Female");
return txtData;
}
// This will be executed when the document is ready
$(function(){
// This will act when the submit BUTTON is clicked
$("#formToSave").submit(function(event){
event.preventDefault();
var txtData = buildData();
window.location.href="data:application/octet-stream;base64,"+Base64.encode(txtData);
});
// This will act when the submit LINK is clicked
$("#submitLink").click(function(event){
var txtData = buildData();
$(this).attr('download','sugguestedName.txt')
.attr('href',"data:application/octet-stream;base64,"+Base64.encode(txtData));
});
});
<!DOCTYPE html>
<html>
<head><title></title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="base64.js"></script>
</head>
<body>
<form method="post" action="" id="formToSave">
<dl>
<dt>Name:</dt>
<dd><input type="text" id="nameField" value="Sample" /></dd>
<dt>Last Name:</dt>
<dd><input type="text" id="lastNameField" value="Last Name" /></dd>
<dt>Gender:</dt>
<dd><input type="radio" checked="checked" name="gender" value="M" id="genderMale" />
Male
<input type="radio" checked="checked" name="gender" value="F" />
Female
</dl>
<p>Save as TXT</p>
<p><button type="submit"><img src="http://www.suttonrunners.org/images/save_icon.gif" alt=""/> Save as TXT</button></p>
</form>
</body>
</html>
BEST solution if you ask me is this.
This will save the file with the file name of your choice and automatically in HTML or in TXT at your choice with buttons.
Example:
function download(filename, text) {
var pom = document.createElement('a');
pom.setAttribute('href', 'data:text/plain;charset=utf-8,' +
encodeURIComponent(text));
pom.setAttribute('download', filename);
pom.style.display = 'none';
document.body.appendChild(pom);
pom.click();
document.body.removeChild(pom);
}
function addTextHTML()
{
document.addtext.name.value = document.addtext.name.value + ".html"
}
function addTextTXT()
{
document.addtext.name.value = document.addtext.name.value + ".txt"
}
<html>
<head></head>
<body>
<form name="addtext" onsubmit="download(this['name'].value, this['text'].value)">
<textarea rows="10" cols="70" name="text" placeholder="Type your text here:"></textarea>
<br>
<input type="text" name="name" value="" placeholder="File Name">
<input type="submit" onClick="addTextHTML();" value="Save As HTML">
<input type="submit" onClick="addTexttxt();" value="Save As TXT">
</form>
</body>
</html>
From what I understand, You have to save a user's input locally to a text file.
Check this link. See if this helps.
Saving user input to a text file locally
This will work to both load and save a file into TXT from a HTML page with a save as choice
<html>
<body>
<table>
<tr><td>Text to Save:</td></tr>
<tr>
<td colspan="3">
<textarea id="inputTextToSave" cols="80" rows="25"></textarea>
</td>
</tr>
<tr>
<td>Filename to Save As:</td>
<td><input id="inputFileNameToSaveAs"></input></td>
<td><button onclick="saveTextAsFile()">Save Text to File</button></td>
</tr>
<tr>
<td>Select a File to Load:</td>
<td><input type="file" id="fileToLoad"></td>
<td><button onclick="loadFileAsText()">Load Selected File</button><td>
</tr>
</table>
<script type="text/javascript">
function saveTextAsFile()
{
var textToSave = document.getElementById("inputTextToSave").value;
var textToSaveAsBlob = new Blob([textToSave], {type:"text/plain"});
var textToSaveAsURL = window.URL.createObjectURL(textToSaveAsBlob);
var fileNameToSaveAs = document.getElementById("inputFileNameToSaveAs").value;
var downloadLink = document.createElement("a");
downloadLink.download = fileNameToSaveAs;
downloadLink.innerHTML = "Download File";
downloadLink.href = textToSaveAsURL;
downloadLink.onclick = destroyClickedElement;
downloadLink.style.display = "none";
document.body.appendChild(downloadLink);
downloadLink.click();
}
function destroyClickedElement(event)
{
document.body.removeChild(event.target);
}
function loadFileAsText()
{
var fileToLoad = document.getElementById("fileToLoad").files[0];
var fileReader = new FileReader();
fileReader.onload = function(fileLoadedEvent)
{
var textFromFileLoaded = fileLoadedEvent.target.result;
document.getElementById("inputTextToSave").value = textFromFileLoaded;
};
fileReader.readAsText(fileToLoad, "UTF-8");
}
</script>
</body>
</html>
You can use localStorage to save the data for later use, but you can not save to a file using JavaScript (in the browser).
To be comprehensive:
You can not store something into a file using JavaScript in the Browser, but using HTML5, you can read files.
Or this will work too the same way but without a save as choice:
<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>//<![CDATA[
window.onload=function(){
(function () {
var textFile = null,
makeTextFile = function (text) {
var data = new Blob([text], {type: 'text/plain'});
// If we are replacing a previously generated file we need to
// manually revoke the object URL to avoid memory leaks.
if (textFile !== null) {
window.URL.revokeObjectURL(textFile);
}
textFile = window.URL.createObjectURL(data);
return textFile;
};
var create = document.getElementById('create'),
textbox = document.getElementById('textbox');
create.addEventListener('click', function () {
var link = document.getElementById('downloadlink');
link.href = makeTextFile(textbox.value);
link.style.display = 'block';
}, false);
})();
}//]]>
</script>
</head>
<body>
<textarea id="textbox">Type something here</textarea> <button id="create">Create file</button> <a download="info.txt" id="downloadlink" style="display: none">Download</a>
<script>
// tell the embed parent frame the height of the content
if (window.parent && window.parent.parent){
window.parent.parent.postMessage(["resultsFrame", {
height: document.body.getBoundingClientRect().height,
slug: "qm5AG"
}], "*")
}
</script>
</body>
</html>
You cannot save it as local file without using server side logic. But if that fits your needs, you could look at local storage of html5 or us a javascript plugin as jStorage
Answer is YES
<html>
<head>
</head>
<body>
<script language="javascript">
function WriteToFile()
{
var fso = new ActiveXObject("Scripting.FileSystemObject");
var s = fso.CreateTextFile("C:\\NewFile.txt", true);
var text=document.getElementById("TextArea1").innerText;
s.WriteLine(text);
s.WriteLine('***********************');
s.Close();
}
</script>
<form name="abc">
<textarea name="text">FIFA</textarea>
<button onclick="WriteToFile()">Click to save</Button>
</form>
</body>
</html>