I have the following line of code here which makes a user text appear upon clicking the send button (to simulate chat messages being sent)
<script>
$('#subbut').click(function(){
var user_msg = $("#user_msg").val();
$("#msg").append('<p>User says:'+user_msg+'</p>');
</script>
<body>
<div id="msg"></div>
<input type="text" name="user_msg" id="user_msg">
<input type="submit" value="Submit" id="subbut">
</body>
However I wish to do this for input of images too.
<body>
<div id="msg"></div>
<input type="file" name="newImage" id="upload-photo">
<input type="submit" value="Submit" id="subbut">
</body>
How do you access the image and append it (to display the image) to the #msg div when the #subbut button is clicked? I've looked at something similar here Preview an image before it is uploaded but I can't seem to adapt it.
<div id="image-wrapper"></div>
<input id="upload-image" type="file" accept=".jpg"/>
<input id="subbut" type="submit" value="Submit"/>
<script>
var _URL = window.URL || window.webkitURL;
$("#subbut").click(function () {
var file;
var image;
if ((file = $("#upload-image")[0].files[0])) {
image = new Image();
image.onload = function () {
$("#image-wrapper").append(this);
$(this).attr("id", "image");
}
image.src = _URL.createObjectURL(file);
}
});
</script>
<input type="file" id="inputFileToLoad" onchange="chnageimgupdate()" />
function loadImageFileAsURL()
{
var filesSelected = document.getElementById("inputFileToLoad").files;
if (filesSelected.length > 0)
{
var fileToLoad = filesSelected[0];
if (fileToLoad.type.match("image.*"))
{
var fileReader = new FileReader();
fileReader.onload = function(fileLoadedEvent)
{
var imageLoaded = document.createElement("img");
imageLoaded.src = fileLoadedEvent.target.result;
document.body.appendChild(imageLoaded);
};
fileReader.readAsDataURL(fileToLoad);
}
}
}
Related
Right now I have a url that displays an image when it's loaded. However, there will be an option for this image to be replaced via a form input. I would like the uploaded image to be displayed as soon as it's uploaded so it can be evaluated by the user.
I'm trying to accomplish this via jQuery, but I can't get it to work.
Here's my code:
HTML:
<div class="form-group">
<label for="Image">Image</label>
<input type="file" id="Image" name="Image" accept="image/*">
<img src="..\{{ workshop_info[4] }}" id="output">
</div>
JQuery:
<script>
$(document).ready(function() {
$("#Image").change(function(e){
$("#output").attr("src", e.target.files[0]);
});
});
</script>
You can do this by using FileReader functionality.
I have recreated your example which displays an image when it's loaded
Once i upload my own image by clicking choose file and selected the file. That file will be getting previewed after selection with that image load_images div i created.
As soon as the file is selected i am replace the src of your existing image to the new src which come from readAsDataURL
You can read more about FileReader here in detail.
Working Demo: https://jsfiddle.net/usmanmunir/w5cbgLsk/
Run snippet below to see it working.
$(function() {
//Preview image function
var previewImage = function(image) {
if (image.files) {
//Check all images
var filesAmount = image.files.length;
for (i = 0; i < filesAmount; i++) {
var reader = new FileReader();
reader.onload = function(event) {
//Replace images on form upload selected image
$('#output').attr('src', event.target.result)
}
reader.readAsDataURL(image.files[i]);
}
}
};
//Select image and call imagePreview function
$('#Image').on('change', function() {
previewImage(this);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-group">
<label for="Image">Image</label>
<input type="file" id="Image" name="Image" accept="image/*">
<div class="load_images">
<img src="http://mandarinazul.co/images/mandarinas.png" id="output">
</div>
</div>
<img src="../yourimage/path/image.jpeg" onclick="previmg()" id="displayimage" />
<input type="file" class="form-control" onchange="selectedimg(this)" id="selectphoto" style="display: none" name="photo">
</div>
function previmg(){
document.querySelector('#selectphoto').click();
}
function selectedimg(e){
if(e.files[0]) {
var reader = new FileReader();
reader.onload = function(e) {
document.querySelector('#displayimage').setAttribute('src', e.target.result);
}
reader.readAsDataURL(e.files[0]);
}}
OR you can try this too,
<input type="file" onchange="previewFile()"><br>
<img src="" height="200" alt="image has to be load">
function previewFile() {
const preview = document.querySelector('img');
const file = document.querySelector('input[type=file]').files[0];
const reader = new FileReader();
reader.addEventListener("load", function () {
preview.src = reader.result;
}, false);
if (file) {
reader.readAsDataURL(file);
}}
try this, both will work charm if any doubt feel free to ask.:-)
HTML Code:
<input type="file" name="img1" id="img1" required>
<input type="file" name="img2" id="img2">
<input type="file" name="img3" id="img3">
<input type="file" name="img4" id="img4">
jQuery Code:
for(var i = 1; i <= 4; i++){
if($("#img"+i).val() != ''){
file = document.getElementById('img' + i).files[0];
fileread(file);
}
}
function fileread(file){
var result = '';
reader = new FileReader();
reader.onload = function(){
result = reader.result;
//return result;
localStorage.setItem("lostimage1", result);
}
reader.readAsDataURL(file);
}
I want to read multiple files when user click on submit button. but it not working. How can I resolve this error? please help me.
Using Jquery and each() method I suggest this:
var checkValue;
var valueArray=[];
$('#button').on('click',function(){
$('input').each(function(){
checkValue=$(this).val();
if(checkValue===''){
return;
}
valueArray.push(checkValue);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file" name="img1" id="img1" required>
<input type="file" name="img2" id="img2">
<input type="file" name="img3" id="img3">
<input type="file" name="img4" id="img4">
<button id="button">Click Me</button>
Attach click event to <input type="submit">, call event.preventDefault() to prevent <form> submission, use .each() to iterate <input type="file"> elements, pass this.files[0] to readfile function.
Adjust within FileReader load handler to not overwrite same key at localStorage.
FileReader throws an error if a Blob or File object is not passed as parameter to .readAsDataURL(), for example, ifis clicked andfilereadis called in loop and one ofelements.filesproperty doe not containFileobject inFileList. Check if element.fileshas.lengthgreater than0before callingfilereadreferencing the.files[0]property of the current` element.
$(function() {
function fileread(file, id) {
var reader = new FileReader();
reader.onload = function() {
localStorage.setItem("lostimage" + id, reader.result);
}
reader.readAsDataURL(file);
}
$("input[type=submit]").on("click", function(e) {
e.preventDefault();
$(":file[id^=img]").each(function() {
if (this.files.length) fileread(this.files[0], this.id.replace(/\D/g, ""))
})
});
});
plnkr http://plnkr.co/edit/1Sec8uWlK2pbXMTlfpCj?p=preview
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>
In my code I want to accept only image file.otherwise it will not accept and will give alert that its not image file.
I have done below code in jsfiddle:--
jsfiddle link
but the problem is it..It is not giving any message.what am I doing wrong?
https://jsfiddle.net/weufx7dy/2/
You forgot to add id on file element
<input type="file" id="file" name="fileUpload" size="50" />
You had used
var image =document.getElementById("file").value;
but forgot to give id to file control so give that
<input type="file" name="fileUpload" id="file" size="50" />
and try following code in w3schools tryit browser and use onClick event on submit button instead of onSubmit
<!DOCTYPE html>
<html>
<body>
<div align="center">
<form:form modelAttribute="profilePic" method="POST"enctype="multipart/form-data" action="/SpringMvc/addImage">
<input type="file" name="fileUpload" id="file" size="50" />
<input type="submit" value="Add Picture" onClick="Validate();"/>
</form:form>
</div>
<script>
function Validate(){
var image =document.getElementById("file").value;
if(image!=''){
var checkimg = image.toLowerCase();
if (!checkimg.match(/(\.jpg|\.png|\.JPG|\.PNG|\.gif|\.GIF|\.jpeg|\.JPEG)$/)){
alert("Please enter Image File Extensions .jpg,.png,.jpeg,.gif");
document.getElementById("file").focus();
return false;
}
}
return true;
}
</script>
</body>
</html>
Use this :
userfile.addEventListener('change', checkFileimg, false);
function checkFileimg(e) {
var file_list = e.target.files;
for (var i = 0, file; file = file_list[i]; i++) {
var sFileName = file.name;
var sFileExtension = sFileName.split('.')[sFileName.split('.').length - 1].toLowerCase();
var iFileSize = file.size;
var iConvert = (file.size / 10485760).toFixed(2);
if (!(sFileExtension === "jpg")) {
txt = "File type : " + sFileExtension + "\n\n";
txt += "Please make sure your file is in jpg format.\n\n";
alert(txt);
document.getElementById('userfile').value='';
}
}
}
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>