How to get image instead of image name in html using file input type. I have used the css file for positioning the image file. I have tried all the sorts of code given... Please help.
<input type="file" name="photo" id="photo" onchange="readURL()"/>
function readURL()
{
document.getElementById('previewimage').style.display='block';
}
function readURL()
{
if (document.getElementById('photo').files && document.getElementById('photo').files[0]) {
var reader = new FileReader();
reader.onload = function(e) {
document.getElementById('previewimage').src = e.target.result;
};
reader.readAsDataURL(document.getElementById('photo').files[0]);
}
}
function openFiledialog(){
document.getElementById('photo').click();
}
//
<input type='button' onclick='openFiledialog()' value='photo'/>
<input type="file" style='display:none;' name="photo" id="photo" onchange="readURL()"/>
Related
I have two buttons ... when clicked they display some text in a input field. I use some simple javascript to select which text to display, the one defined under the button with id="blabla1" or the one under the button with id="blabla2".
Is it possible to display the text defined in an external .txt file?
It is working fine with the text defined as value under the input button:
<input type="hidden" id="SupSite1Title" value="Subsite1 Title!"><br>
but i want text from a txt file instead.
<body>
<div id="leftnav">
<ul>
<li><input type="text" id="TextField1"><br><br></li>
</ul>
</div>
<div id="rightnav">
<ul>
<li><button id="blabla1" onclick="myFunction1()">Side1</button></li>
<li><button id="blabla2" onclick="myFunction2()">Side2</button></li>
</ul>
</div>
<input type="hidden" id="SupSite1Title" value="Subsite1 Title!"><br>
<input type="hidden" id="SupSite2Title" value="Subsite2 Title!"><br>
<script>
function myFunction1() {document.getElementById("TextField1").value =document.getElementById("SupSite1Title").value;
}
</script>
<script>
function myFunction2() {document.getElementById("TextField1").value =document.getElementById("SupSite2Title").value;
}
</script>
If you want to display the text content of the .txt file ... you can use an API called FileReader API (you need to check if your browser supports that)
here is how you can do it :
UPDATED :
var file1 = document.getElementById('file1');
var file2 = document.getElementById('file2');
document.getElementById('bOne').addEventListener("click", function(){getFile(file1)})
document.getElementById('bTwo').addEventListener("click", function(){getFile(file2)})
function getFile(target) {
const input = target;
if ('files' in input && input.files.length > 0) {
placeFileContent(
document.getElementById('display'),
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)
})
}
label {
display : block;
margin-top : 40px;
margin-bottom : 20px;
}
<label for="file1">Upload file 1 : </label>
<input type="file" accept=".txt" id="file1" name="file1">
<label for="file2">Upload file 2 : </label>
<input type="file" accept=".txt" id="file2" name="file2">
<button id="bOne">Display file1</button>
<button id="bTwo">Display file2</button>
<label for="file2">Selected file : </label>
<input type="text" id="display" for="display">
METHOD N°2 (data fetching from a server) :
function fetchData(buttonNumber) {
var btn1 = document.getElementById('b1')
var btn2 = document.getElementById('b2')
var display = document.getElementById('display')
//fetching data
if (buttonNumber == 1) {
//replace 'file1.txt' with your file URL
fetch('file1.txt').then(x => {
x.text().then(function(text) {
display.value = text
});
})
} else {
//replace 'file2.txt' with your file URL
fetch('file2.txt').then(x => {
x.text().then(function(text) {
display.value = text
});
})
}
}
#b1,
#b2 {
display: block;
margin: 40px;
}
<button id="b1" onclick="fetchData(1)">Get file 1 and show it</button>
<button id="b2" onclick="fetchData(2)">Get file 2 and show it</button>
<label for="file2">Selected file : </label>
<input type="text" id="display" for="display">
If you want to read the contents of a text file you cannot load it from local file system. You should put it on server and load it from there.
Give the input field the attributes type="file" and accept=".txt", and that should work
<input type="file" accept=".txt" />
And you can read this .txt file using node.js(Also you can read it with vanilla js), But i prefer node.js like this
const fs = require('fs');
const fileData = fs.readFileSync('fileName.txt', 'utf-8');
console.log(fileData) // Whatever inside .txt file
Update according to comment:
Suppose in your project folder, you have one index.html file and one index.js file. Create two .txt file named as file1.txt and file2.txt And write something on those file. NOTE: For simplicity i am writing solution using jQuery.
index.html
<body>
<p id="text-field"></p>
<button id="btn1">Button 1</button>
<button id="btn2">Button 2</button>
</body>
index.js
const fs = require('fs');
let fileData = '';
$('#btn1').click(()=> {
fileData = fs.readFileSync('file1.txt', 'utf-8');
$('#text-field').append(fileData);
});
$('#btn2').click(()=> {
fileData = fs.readFileSync('file2.txt', 'utf-8');
$('#text-field').append(fileData);
});
That's it. According to button click text will be append into p element.
You can handle two button click with one function also, like this
$('button').click(event => {
event.stopImmediatePropagation();
event.stopPropagation();
if($(event.target).attr('id') === 'btn1') {
fileData = fs.readFileSync('file1.txt', 'utf-8');
$('#text-field').append(fileData);
}else if($(event.target).attr('id') === 'btn2') {
fileData = fs.readFileSync('file2.txt', 'utf-8');
$('#text-field').append(fileData);
}
});
So the file input opens up fine and I can choose a file. I also now that the file upload works and that it binds a file. But the ng-change event is never triggered.
<img class="profile-pic" ng-click="addHeaderImage()" ng-src="{{applyform.UseProfilePic}}"/>
<input type="file" ng-change="uploadHeader()" style="display: none" id="headerinput" ngf-select ng-model="file" ngf-multiple="false"/>
$scope.addHeaderImage = function () {
document.getElementById("headerinput").click();
}
$scope.uploadHeader = function () {
//$scope.loading = true;
var file = document.getElementById("headerinput").files[0];
var reader = new FileReader();
console.log("TJAABAB");
reader.addEventListener("load",
function () {
//item.Image = reader.result;
console.log("UPLOAD");
console.log(reader.result);
$scope.$apply();
//$scope.updateQuoteHeader(item);
//$scope.loading = false;
},
false);
if (file) {
reader.readAsDataURL(file);
}
}
so the function upload header is never triggered when I choose a file. Why is that?
Instead of ng-change, try onchange:
<input type="file" onchange="angular.element(this).scope().uploadHeader()" style="display: none" id="headerinput" ngf-select ng-model="file" ngf-multiple="false"/>
i'm trying to convert an image taken from a form to blob or base64 format, for this, i'm using FileReader of Javascript. My form is this:
<form id="form" enctype="multipart/form-data" method="POST" class="wizard-big">
<div class="form-group">
<label>Adjuntar Logo *</label>
<input id="archLogo" name="archLogo" type="file">
</div>
<form>
Ok, my script of javascript is this:
<script>
$('#archLogo').change(function() {
if ($('#archLogo')[0] && $('#archLogo')[0].files[0]) {
var FR= new FileReader();
FR.onload = function(e) {
console.log(e.target.result);
};
FR.readAsDataURL( $('#archLogo')[0].files[0] );
}
},false);
</script>
The problem is that the console.log is not printing nothing, so, the conversion is not working, what am I doing wrong?
EDIT:
if ($('#archLogo')[0] && $('#archLogo')[0].files[0])
{
var FR= new FileReader();
FR.onload = function(e) {
logoBlob=e.target.result;
alert(logoBlob);
};
FR.readAsDataURL( $('#archLogo')[0].files[0] );
}
This works
I need one help.I have one image icon, when user will select that icon the file dialog will open and user will select the image.After selecting the image the image should display on that image icon.I am explaining my code below.
<div class="image-upload">
<label for="bannerimage">
<img src="{{attachImage}}"/>
</label>
<input type="file" data-size="lg" name="bannerimage" id="bannerimage" ng-model="file" ngf-pattern="'image/*'" accept="image/*" ngf-max-size="2MB" ngf-min-height="100" ngf-resize="{width: 100, height: 100}" custom-on-change="uploadFile" required="required" ngf-select="onFileSelect($file);" ngf-multiple="true">
</div>
my controller side code is given below.
$scope.attachImage="upload/logo.png";
$scope.uploadFile = function(event){
console.log('event',event.target.files);
var files = event.target.files;
for (var i = 0; i < files.length; i++) {
var file = files[i];
var reader = new FileReader();
reader.onload = $scope.imageIsLoaded;
reader.readAsDataURL(file);
}
};
$scope.imageIsLoaded = function(e){
$scope.$apply(function() {
//var data={'image':e.target.result};
// $scope.stepsModel.push(data);
//$scope.myImage=e.target.result;
$scope.attachImage='';
$scope.attachImage=$scope.myImage;
});
});
Here i need when user will select the image the image will display on that particular image icon.Please help me.
I believe you need to use reader.onloadend instead of reader.onload
reader.onloadend = function () {
// set $scope.attachImage to reader.result;
}
I want to preview multiple images before upload. Secondly I want to remove/deselect the selected file if I choose wrong file. I am working on jquery code but it preview one image at a time. Also I want to select multiple images at a single time.
Here is the jquery code.
$(document).ready(function() {
//To add new input file field dynamically, on click of "Add More Files" button below function will be executed
$('#add_more').click(function() {
$(this).before($("<div/>", {id: 'filediv'}).fadeIn('slow').append(
$("<input/>", {name: 'file[]', type: 'file', id: 'file'}),
$("<br/><br/>")
));
});
//following function will executes on change event of file input to select different file
$('body').on('change', '#file', function(){
if (this.files && this.files[0]) {
abc += 1; //increementing global variable by 1
var z = abc - 1;
var x = $(this).parent().find('#previewimg' + z).remove();
$(this).before("<div id='abcd"+ abc +"' class='abcd'><img id='previewimg" + abc + "' src=''/></div>");
var reader = new FileReader();
reader.onload = imageIsLoaded;
reader.readAsDataURL(this.files[0]);
$(this).hide();
$("#abcd"+ abc).append($("<img/>", {id: 'img', src: 'x.png', alt: 'delete'}).click(function() {
$(this).parent().parent().remove();
}));
}
});
//To preview image
function imageIsLoaded(e) {
$('#previewimg' + abc).attr('src', e.target.result);
};
$('#upload').click(function(e) {
var name = $(":file").val();
if (!name)
{
alert("First Image Must Be Selected");
e.preventDefault();
}
});
});
Here is the HTML code
<div id="formdiv">
<h2>Multiple Image Upload Form</h2>
<form enctype="multipart/form-data" action="" method="post">
First Field is Compulsory. Only JPEG,PNG,JPG Type Image Uploaded. Image Size Should Be Less Than 100KB.
<hr/>
<div id="filediv"><input name="file[]" multiple type="file" id="file"/></div><br/>
<input type="button" id="add_more" class="upload" value="Add More Files"/>
<input type="submit" value="Upload File" name="submit" id="upload" class="upload"/>
</form>
<br/>
<br/>
<!-------Including PHP Script here------>
<?php include "upload.php"; ?>
</div>
maybe you can see this topic , I think it has what you need.
Create live preview of image (before upload it) using JQuery
also you can give a try with that
http://www.aspsnippets.com/Articles/Show-Display-image-preview-before-upload-using-jQuery.aspx
You can find examples on http://www.fyneworks.com/jquery/multifile/
Maybe you can extract the parts of their code to write your custom.
For images preview you can use the URL.createObjectURL javascript function . Example:
$('body').on('change', '#file', function(){
if (this.files && this.files[0]) {
var URL = window.URL || window.webkitURL;
var img = $('<img />').attr('src', URL.createObjectURL(this.files[0] ) );
}
});
If you need a full uploader you can also try this: http://www.albanx.com/ajaxuploader/ or other online examples