I want to add an input box (a placeholder) where the user could paste a screenshot into. img is not going to do it as it requires the screenshot to be saved into an image file, then the scr be directed to it. Too cumbersome. I want a simple copy (or print screen) and paste to do it.
I modified the code from the following discussion:
HTML Paste Clipboard Image to File Input,
but it does not work.
<form id="new_document_attachment" method="post">
<div class="actions"><input type="submit" name="commit" value="Submit" /></div>
<img src="" alt="Screen Shot" id="image_attachment_doc">
</form>
<script>
const form = document.getElementById("new_document_attachment");
const imageInput = document.getElementById("image_attachment_doc");
imageInput.addEventListener('change', () => {
form.submit();
});
window.addEventListener('paste', e => {
imageInput.src = e.clipboardData.files;});
</script>
You need to convert the image data in the File object into a Data URL.
Thanks to Loading an image to a <img> from <input file>
Your example is also a bit limited in that although the image would show up, the page would reload almost immediately.
In the example below the form is not submitted.
const log = document.getElementById("log");
window.addEventListener('paste', e => {
var files = e.clipboardData.files;
//Put the file into an input so it will be included with the form submit
document.getElementById("files").files = files;
//This won't work because the src holds a string
//and the file object becomes serialized into "[object%20File]"
//This can be seen in the console
document.getElementById("img").src = files[0];
//Show image by loading it as an DataURL
var fr = new FileReader();
fr.onload = function() {
document.getElementById("img").src = fr.result;
}
fr.readAsDataURL(files[0]);
});
<form id="form" method="post">
<img id="img" alt="Screen Shot">
<input type="file" name="files" id="files" />
<input type="submit" />
</form>
<p>Press Ctrl+V to paste an image into this window</p>
Related
Hi i have a registration form with a avatar upload.
The form is working perfectly and i am happy with it, but i have 1 problem.
After i upload A avatar image and go onto the next page i can then go back to the registration page and the image remains in memory...
But i have no way of displaying it as i have no idea how to access the image as it is in memory somewhere.
But i can at this point complete my registration again without having to upload A image And the image is then displayed on the following page..
(the "required" is ignored in the form also as it has a file in memory)
Not sure if this explanation is doing me any favors but if any 1 can see from my code how i could again display the image if its in memory after a page refresh.
Thank you.
Simple Version.
"How Do I Access The Uploaded Image if Still in Memory And Display It Again On Page Refresh..."
<form id='login-form' name='formsub' class='form' action='../imageupload/formfillsignup.php' method='post' enctype='multipart/form-data'>
<label id='usernamelabel'>UserName</label>
<input id='em1' type='name' name='username' placeholder='3-15 Characters ' pattern='^[a-zA-Z][a-zA-Z0-9-_\. ]{3,15}$' autocomplete='new-password' required onChange='checkusername();' class='imp'/>
<label id='emaillabel'>Email</label>
<input id='em2' type='email' autocomplete='new-email' placeholder='Standard Email Format Required' name='email' pattern='[a-zA-Z0-9]+#[a-zA-Z0-9]+\.[a-zA-Z]{2,}'required onChange='alertemail();' class='imp' />
<label id='passwordlabel'>PassWord</label> <div class='reveal' id='revealPass' onclick='revealpasswords();' title='show/hide Passwords'></div>
<input id='p1' type='password' autocomplete='new-password' placeholder='1 UpperCase + 1 Number' name='password' pattern='(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}' required onChange='alertpass();' class='imp' />
<label id='confirmpasswordlabel'>Confirm PassWord</label>
<input id='p2' type='password' autocomplete='new-password' placeholder='1 UpperCase + 1 Number ' name='confirmpassword' pattern='(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}' required onChange='checkPasswordMatch();' class='imp'/>
<label class="custom-file-upload">
<input type="file" id="file1" name="avatar" accept="image/*" required />
<h7>Upload Avatar</h7>
</label>
<div class='image' id='imagediv'></div>
<button class='signupbutton' type='button' onclick='checkfile();'>Register</button>
</form>
<script>
$(function () {
$('input[type=file]').change(function () {
var val = $(this).val().toLowerCase(),
regex = new RegExp("(.*?)\.(jpg|jpeg|png|gif|bmp|JPG|JPEG|PNG|GIF|BMP)$");
if (!(regex.test(val))) {
$(this).val('');
$("#signintext").text("JPG JPEG PNG BMP GIF ONLY"), $("#signintext").css({"color":"#f40351"}), $( "#signintext" ).addClass( "errorglow" );
$('#imagediv').css('background-image', 'url("../images/mainpage/uploadimage.jpg")');
$('#imagediv').css('opacity','0.2');
}else
{
if (regex.test(val)) {
$("#signintext").text("Avatar Upload Completed"), $("#signintext").css({"color":"#03f4bc"}) , $( "#signintext" ).removeClass( "errorglow" );
var file = this.files[0];
var reader = new FileReader();
reader.onloadend = function () {
$('#imagediv').css('background-image', 'url("' + reader.result + '")');
$('#imagediv').css('opacity','1');
}
if (file) {
reader.readAsDataURL(file);
} else {
var file1=document.getElementById('file1');
file1.files.length == 0;
$(file1).val('');
return false;
}
}
}
});
</script>
When the page is refreshed the DOM is completely rebuilt. To retain the image across refreshes use localStorage. When the image is uploaded for the first time you would save it locally. When the page loads you would check localStorage for the existence of an image; if the image is present then you would load it into your image frame.
You need to save the image in base64 encoding. To do this listen for the file upload change event, and then use FileReader to encode as a data URL.
document.getElementById("file1").addEventListener('change', function() {
var file = this.files[0];
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function () {
localStorage.setItem("profileImageData", reader.result);
};
} );
When the page is loaded you need to check localStorage and add the encoded image. Loading an encoded image as a CSS background in JavaScript doesn't work so you'll have to insert it as an image.
window.onload = function() {
var profileImage = localStorage.getItem("profileImageData");
if (profileImage !== null) {
document.getElementyId("imagediv").innerHTML = "<img src='" + profileImage + "'>";
}
}
I am in need of an HTML form in which the input would add onto a URL as I have a preexisting API.
Basically, I need an HTML form which would fill in a variable within a URL.
Say I had an API with the URL "https://example.com/api/api?item=<FILL THIS IN WITH THE INPUT>&auth=AUTHENTICATIONtoken", I need to have the input of the HTML form replace "<FILL THIS IN WITH THE INPUT>".
I recall finding a way to do this before-but I can't seem to find it anymore.
You can do this with JavaScript.
If this is your form:
<form onsubmit="changeFormAction()">
<input type="text" id="item">
<button type="submit" id="submitButton">Submit</button>
</form>
and if you have this in your JavaScript:
function changeFormAction() {
var item = document.getElementById("item").value;
var form = this;
form.action = "https://example.com/api/api?item=" + item + "&auth=AUTHENTICATIONtoken";
form.submit();
}
Then the function will automatically change the form action by adding the item specified by the form input.
Demo:
function changeFormAction(event) {
var item = document.getElementById("item").value;
var form = this;
form.action = "https://example.com/api/api?item=" + item + "&auth=AUTHENTICATIONtoken";
// for demonstration, don't actually submit the form, just print out the form action
console.log(form.action);
event.preventDefault();
}
<form onsubmit="changeFormAction(event)">
<input type="text" id="item">
<button type="submit" id="submitButton">Submit</button>
</form>
I have made a MVC ASP.NET CORE 1.0 Webapp.
It will be used as offline app, i.e: server will be localhost always.
All I want to do is let the user click on a button called "browse" on the html page. and then a filepicker appears in front of them so they can just pick a file.
and then all I want to do is read that text file and do some logic with it later on.
I have tried Following
HTML
<form asp-action="Mark" asp-controller="Home" method="post" enctype="multipart/form-data">
<div class="form-group">
<label class="btn btn-primary" for="my-file-selector">
<input id="my-file-selector" type="file" name="file" style="display:none;" onchange="$('#upload-file-info').html($(this).val());">
Browse
</label>
<span class='label label-info' id="upload-file-info"></span>
</div>
<button type="submit" class="btn btn-default">Submit</button>
Controller Code
[HttpPost]
public IActionResult Mark(IFormFile file)
{
return View();
}
IMPORTANT :
the above code works fine to upload the file, but I dont want to upload any file as it takes too much time and unnecessary memory space, I only want to read the contents of the text file which user selected.
Thanks In Advance
You can do that by using FileReader in JavaScript.
Here is an example:
HTML:
<input type="file" id="file-input" />
JavaScript:
function readFile(e) {
var file = e.target.files[0];
if (!file) {
return;
}
var reader = new FileReader();
reader.onload = function(e) {
var contents = e.target.result; // here is your file content
};
reader.readAsText(file);
}
document.getElementById('file-input').addEventListener('change', readFile, false);
That will take care of reading file content on the client site but if you need to do that in the back end (controller) then you've to upload the file.
I have website with form I'am uploading image from using Html.BeginForm() through the controller. Uploaded image saves correctly (i see it in folder) but I can't see it on website. To do so I have to reload entire webbrowser.
How can I make image showing on my website after uploading? Website shows this image few times, on different views, always by <img scr="imagePatch"/>. New image just saves itself with the same name as previous one, replacing it.
there are many ways to do this
you can use html file api inside your form.
$(document).ready(function(){
// render the image in our view
function renderImage(input,file) {
// generate a new FileReader object
var reader = new FileReader();
// inject an image with the src url
reader.onload = function(event) {
the_url = event.target.result;
$('.img-preview__').remove();
$(input).after("<img class='img-preview__' src='" + the_url + "' />")
}
// when the file is read it triggers the onload event above.
reader.readAsDataURL(file);
}
// handle input changes ... you can change selector
$("#the-file-input").change(function(event) {
// grab the first image in the FileList object and pass it to the function
renderImage(event.target,this.files[0]);
});
});
this will work nice . either you can make your image preview look like better.
for image preview element use this css code
img.img-preview__ {
width: 120px;
border: 3px solid #ddd;
border-radius: 3px;
display: inline-block;
}
for example
<h2>Create</h2>
#using (Html.BeginForm("Create", "Image", null, FormMethod.Post,
new { enctype = "multipart/form-data" })) {
<fieldset>
<legend>Image</legend>
<div class="editor-label">
#Html.LabelFor(model => model.ImagePath)
</div>
<div class="editor-field">
<input id="the-file-input" title="Upload a product image"
type="file" name="file" />
</div>
<p><input type="submit" value="Create" /></p>
</fieldset>
}
I hope this help
I have an iframe in the content area:
<iframe name="my_iframe" frameBorder="0" height="200" src="about:blank"></iframe>
I have a submit-button under it:
<form action="includes/action.php" method="post" target="my_iframe">
<input type="submit" value="Submit">
</form>
And I want some checkboxes in another area:
<form action="includes/action.php" method="post" target="my_iframe">
<input type="checkbox" name="option">
</form>
But it doesn't work, the submit-button works but it doesn't send the checkbox.
I can't put everything in one -tag because I want the checkbox in a sidepanel of the main-view and the submit-button on a page that is in another page. (Loaded per ajax? I'm using frameworks7 btw.)
Is it not possible with different form-tags or is it because of the ajax thingy?
EDIT1: I managed to build an example for easier understanding with plunker, it doesn't work with php and I don't have a webspace right now, but you get the idea.
http://plnkr.co/edit/dfqzCbeQWgg9hAyCpGpb
UPDATE 2
To get a cleaner result without the stale cache confusing tests I have updated it, please review newest update:
http://plnkr.co/edit/34KOyh9rIEGV3bXNsD9F?p=preview
UPDATE
Now that I was provided with a very complete and nicely coded demo, I have solved your problem.
http://plnkr.co/edit/Z2I1Q2swIXmFfynalaLB?p=preview
Note: I'm using a test server, so the cache may be stale. Just change the action by adding a number to the end.
Example
change:
http://www.hashemian.com/tools/form-post-tester.php/so_post_chk
to:
http://www.hashemian.com/tools/form-post-tester.php/so_post_chk1
When the checkbox is checked, your result should be cache=on
When the checkbox is not checked, your result should be cache=
You could assign one or more inputs (usually type="hidden") outside of the forms and collect whatever data from anywhere on the page regardless of which form it originated from.
http://plnkr.co/edit/er5RoJ049xSBwtR7gtTI?p=preview
This demo revolves around a simple JS function:
function toOutput(x) {
var str = x.toString();
var out4 = document.getElementById('out4');
out4.value += str;
}
Note the special condition for checkboxes:
if(this.checked) {
toOutput(this.value);
text1.value += this.value;
};
It's needed because when the click event is triggered on a checkbox, it is considered on every click checked and unchecked. I assume that the checkbox value is collected when it's actually checked.
I got option onsubmit form ...
Try it:
Create test.php file:
<form id="myForm" action="includes/action.php" method="post" target="my_iframe">
<input onclick="myFunction()" type="submit" value="Submit">
</form>
<form action="includes/action.php" method="post" target="my_iframe">
<input id="cbopt" type="checkbox" name="option" value="option" checked="checked">
</form>
<script>
function myFunction() {
var y = document.createElement("input");
y.setAttribute("type", "checkbox");
y.setAttribute("value", "option");
y.setAttribute("name", "option");
y.setAttribute("checked", "checked");
document.getElementById("myForm").appendChild(y);
var x = document.getElementById("cbopt").name;
document.getElementById("demo").innerHTML = x;
var z = document.forms.length;
document.getElementById("demo").innerHTML = z;
}
</script>
Code for includes/action.php :
<iframe name="my_iframe" frameBorder="0" height="150" width="555" src="about:blank">
<p id="demo"></p>
</iframe>
<?php
//$site = $_POST['doorde'];
//$url = $_POST['doordie1'];
$opt = $_POST['option'];
echo $opt;
?>
Try and comment me ...
Here's what you can do, copy the values from one form to the other before submitting, making sure you remove fields added previously when you submit again.
<form action="includes/action.php" method="post" target="my_iframe" id="myform">
<input type="submit" value="Submit">
</form>
<form action="includes/action.php" method="post" target="my_iframe" id="otherform">
<input type="checkbox" name="option">
</form>
<iframe name="my_iframe" frameBorder="0" height="200" src="about:blank"></iframe>
<script>
function copyFormFieldsIntoHiddenFields(from, to) {
var elementsAdded = [];
for (var i = 0; i < from.elements.length; i++) {
var nodeToCopy = from.elements[i];
// Unchecked checkboxes do not get sent to server
if (nodeToCopy.type != "checkbox" || nodeToCopy.checked) {
var hiddenField = document.createElement('input');
hiddenField.type = "hidden";
hiddenField.name = nodeToCopy.name;
hiddenField.value = nodeToCopy.value;
to.appendChild(hiddenField);
elementsAdded.push(hiddenField);
}
}
return elementsAdded;
}
var addedFields = [];
document.getElementById('myForm').addEventListener('submit', function() {
// Remove any fields that were previously added
for (var i = 0; i < addedFields.length; i++) {
this.removeChild(addedFields[i]);
}
// Add the new hidden fields
var copyFrom = document.getElementById('otherform');
addedFields = copyFormFieldsIntoHiddenFields(copyFrom, this);
});
</script>