i am trying to make a simple page im HTML/javascript. The point is to check some parameters (width, height...) of an image that the user submit a form. In JS i get the file from the form, and try to "convert" it to an image using Object URL.
Problem happens there, when i load the url into the image .src property, the image does not seem to load well. Its attributes keep the default values (width=0, name =""...) and the .onload event isn't even triggered.
A simplified version of my code is below.
The url works well when i copy/paste it in my browser I get the image I submited. Neither the .onload or .onerror function is called.
I don't get why the image isn't loaded properly. If anyone has a clue I'll be glad if you share it.
function checkData() {
var images = document.getElementsByName('img');
var img = new Image();
img.onload = function() {
alert('the image is drawn');
}
img.onerror = function(e) {
console.log("Not ok", e);
}
img.src = URL.createObjectURL(images[0].files[0]);
if (img.width != 385 || img.height != 345) {
alert("Wrong size");
return false;
}
}
console.log();
<form method=POST name="Form" onsubmit="return checkData()" action="">
Image 1
<input type="file" name="img"><br>
<input type="submit" value="check">
</form>
This will draw a user uploaded image to a canvas. I think that's what you're going for?
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form method=POST name="Form" action="">
Image 1
<input type="file" onchange="previewFile()"><br>
<canvas id="canvas"></canvas>
</form>
<script>
function previewFile() {
var file = document.querySelector('input[type=file]').files[0];
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
if (file) {
ctx.drawImage(file,385,345);
}
}
</script>
</body>
</html>
I believe this to be a duplicate, as mentioned in my comment.
But just out of curiosity, I built a working example below.
You must wait until the image loads before checking its dimensions.
function checkData() {
console.log('checking image size...');
var img = new Image();
var images = document.getElementsByName('img');
var ctx = document.getElementById('canvas').getContext('2d');
img.onload = function() {
if (img.width != 385 || img.height != 345) {
console.log("Wrong size: " + img.width + " X " + img.height);
} else {
ctx.drawImage(this, 20, 20);
console.log("The image is drawn.");
}
}
img.onerror = function(e) {
console.log("Not ok", e);
}
img.src = URL.createObjectURL(images[0].files[0]);
}
var myform = document.getElementById('myform');
myform.addEventListener('submit', function(e) {
e.preventDefault();
checkData();
});
#canvas {
width: 20px;
height: 20px;
}
<form method="post" name="form" id="myform" action="">
Image 1
<input type="file" name="img"><br>
<input type="submit" value="check">
</form>
<canvas id="canvas"></canvas>
Related
I'm parsing an Excel file to an array in JavaScript and I have a simple form with a file upload and check boxes. I'm adapting the code from elsewhere and it runs perfectly as expected immediately on file upload, but I want it to handle the file on clicking submit, not on addEventListener for "change". How can I alter this JavaScript / jQuery so that it executes the handleFile in the same way it does now, but on the form submit click.
I tried multiple methods like
document.getElementById('submit').addEventListener("click", handleFile(oFileIn));
And encapsulating everything beneath setup in:
$('#submit').click(function(){
var oFileIn; ...
});
HTML:
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.12.6/xlsx.full.min.js"></script>
</head>
<body>
<form id="formid" action="form.php" method="POST" enctype="multipart/form-data">
<label><input id="inputX1" type="checkbox" name="x1" value="x1">x1</label><br>
<label><input id="inputX2" type="checkbox" name="x2" value="x2">x2</label><br>
<label><input id="inputX3" type="checkbox" name="x3" value="x3">x3</label><br>
<label><input id="inputX4" type="checkbox" name="x4" value="x4">x4</label><br>
<input id="fileid" type="file" name="filename" />
<input id="submit" type="button" value="submit"/>
</form>
</body>
</html>
JavaScript:
$(document).ready(function() {
setup();
});
function setup() {
var oFileIn;
$(function() {
oFileIn = document.getElementById('fileid');
if(oFileIn.addEventListener) {
oFileIn.addEventListener('change', handleFile, false);
}
});
var rABS = true;
function handleFile(e) {
var files = e.target.files, f = files[0];
var reader = new FileReader();
reader.onload = function(e) {
var data = e.target.result;
if(!rABS) data = new Uint8Array(data);
var workbook = XLSX.read(data, {type: rABS ? 'binary' : 'array'});
// DO STUFF WITH THE FILE HERE AND CHECK BOXES HERE
So if you want to just load the data on a button click all you really need to do is put a click listener on your button instead of a change event on your file input.
Your attempt was close but since we can use the ID of the file input, there is no need to pass anything into handleFile()
I also put in a check to make sure a file is actually there before we go ahead and read it.
Here's an example using jQuery for you
function setup() {
$("#submit").on("click", handleFile);
var rABS = true;
function handleFile() {
var files = $("#fileid").prop("files");
if(files.length === 0){
alert("Please select a file first");
return;
}
var f = files[0];
var reader = new FileReader();
reader.onload = function(e) {
var data = e.target.result;
//continue on with data
}
reader.readAsText(f);
}
}
I have a HTML page allowing a user to take a photo and that photo then shows up on the screen as a canvas image. I want to now send this image to the server to be uploaded, along with other data, using POST method.
JavaScript for displaying image:
<script>
// Elements for taking the snapshot
var video = document.getElementById('video');
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
var dataURL;
//Hide photo elements until user clicks button
$("#snap").hide();
$("#canvas").hide();
$("#video").hide();
//user clicks take photo button
$("#showCam").click(function() {
$(this).hide();
$("#snap").show();
$("#video").show();
if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
navigator.mediaDevices.getUserMedia({
video : true
}).then(function(stream) {
video.src = window.URL.createObjectURL(stream);
video.play();
});
}
});
// Trigger photo take
$("#snap").click(function() {
context.drawImage(video, 0, 0, 640, 480);
$("#canvas").show();
$(this).hide();
$("#video").hide();
//convert canvas image to url format
dataURL = canvas.toDataURL();
});
</script>
HTML Form:
<div id=formContainer>
<form id="myForm" action="insert.php" method="post" enctype="multipart/form-data">
Description
<input type="text" name="fdesc">
<br>
<input type="submit" value="Insert">
</form>
</div>
JQuery to add data to form (For the other data, how would I add image like this?):
<script>
$('#myForm').submit(function() {
var input = $("<input>").attr("type", "hidden").attr("name", 'lat').val(latArray);
$('#myForm').append($(input));
var input = $("<input>").attr("type", "hidden").attr("name", 'lon').val(lonArray);
$('#myForm').append($(input));
//var input = $("<input>").attr("type", "file").attr("name", 'img').val(image);
//$('#myForm').append($(input));
return true;
});
</script>
How would I go about doing this?
You have to add hidden input field of type "file" to your form and the put video element as file in the new input field!
Instead of using html form to POST, you can use https://api.jquery.com/jquery.post/ instead
I did a script that check the image width and remove the image if the width is lesser than certain amount.
The image field is required and after I removed it, it still passed the file validation.
sample: http://jsfiddle.net/AUQYv/3/
<form action="">
<input type="file" id="file" required />
<input type="submit" value="Submit">
</form>
Javascript
var _URL = window.URL || window.webkitURL;
$("#file").change(function (e) {
var file, img;
if ((file = this.files[0])) {
img = new Image();
img.onload = function () {
if(this.width<490||this.height<175){
$("#file").val("").change();
}
};
img.onerror = function () {
alert("not a valid file: " + file.type);
};
img.src = _URL.createObjectURL(file);
}
});
Your conditional statement is setting file = this.files[0]. Change to ==
Edit:
Since both commenters pointed out that I was wrong, replace
$("#file").val("").change():
with
$("#file").replaceWith($("#file").clone());
Try with this.
<form action="" id="form" method="post">
<input type="file" id="file" required accept='image/png, image/gif, image/jpeg, image/jpg'/>
//your button submit
Submit
</form>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript">
//When click the button
$('#submitForm').click(function(){
var validation = true; //Var to validation true
if($('#file').val()){ //There's image?
if($('#file').width()<490 || $('#file').height()<175){
validation = false;
}
}else{
validation = false;
}
//Is true?
if(validation){
$('#form').submit();
}else{
alert("select a image");
}
});
</script>
html code:
<h1>Uploading a photo.</h1>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.js"></script>
<script type="text/javascript">
var p;
var canvas = document.createElement("canvas");
var img1=document.createElement("img");
function converttobyte()
{
p=document.getElementById("file").value;
img1.setAttribute('src', p);
canvas.width = img1.width;
canvas.height = img1.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(img1, 0, 0);
var dataURL = canvas.toDataURL("image/png");
alert("from getbase64 function"+dataURL );
return dataURL;
}
</script>
<form action="UploadFile" method="post" accept-charset="utf-8" name="UploadFileForm"
enctype="multipart/form-data">
<input type="file" id="file" name=""><br>
<input type="submit" value="Upload" onclick="converttobyte">
</form>
Python code:
def UploadFile(request):
if request.method == 'POST':
converttobyte = request.GET['converttobyte'].decode("base64")
#file = request.FILES['avatar']
default_storage.save("%s"%(converttobyte), ContentFile(converttobyte.read()))
return HttpResponse("File uploaded successfully")
else:
return HttpResponse("please upload a file")
what should be a statement that should be added after if request.method== 'post' in order to accept the the function return value in python script.
Please help me. Thanks in advance
Inside your form creates a hidden variable,
<form action="UploadFile" method="post" accept-charset="utf-8" name="UploadFileForm"
enctype="multipart/form-data">
<input type="hidden" id="url" name="url" value="">
<input type="file" id="file" name=""><br>
<input type="submit" value="Upload" onclick="converttobyte">
</form>
Instead of returning the value from java script assign that value to the hidden variable,
function convert_to_byte()
{
p=document.getElementById("file").value;
img1.setAttribute('src', p);
canvas.width = img1.width;
canvas.height = img1.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(img1, 0, 0);
var dataURL = canvas.toDataURL("image/png");
alert("from getbase64 function"+dataURL );
document.getElementById("url").value = dataURL;
}
Then after submit you can use the below code to get the value in python,
if request.method == 'POST':
url_value = request.POST['url']
One way to solve your problem is :
Create a hidden field as follows
<input type="hidden" id="hide" name="URL" value="">
In the javascript function, rather than returning the value, set it for the hidden field
document.getElementById("hide").value = dataURL;
Once the form is submitted, the hidden value goes with it. Access the field using request.GET['URL'] in python code
Hope this solves the problem.
A few problems with your code.
Shouldn't you be calling the method like onclick="converttobyte()" instead ?
In the converttobyte() method you are simply returning the dataURL when the form is submitted but how is that value passed to the POST request ?
You'd need to pass the value with the POST request. You can use a hidden field to achieve this. Try something like this:
Javascript:
<h1>Uploading a photo.</h1>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.js"></script>
<script type="text/javascript">
var p;
var canvas = document.createElement("canvas");
var img1=document.createElement("img");
function converttobyte()
{
p=document.getElementById("file").value;
img1.setAttribute('src', p);
canvas.width = img1.width;
canvas.height = img1.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(img1, 0, 0);
var dataURL = canvas.toDataURL("image/png");
alert("from getbase64 function"+dataURL );
/**Set the value of the raw_bytes input field*/
var form = document.getElementById('uploadForm');
form.raw_bytes.value = dataURL;
}
</script>
<form id="uploadForm" action="UploadFile" method="post" accept-charset="utf-8" name="UploadFileForm"
enctype="multipart/form-data">
<input type="file" id="file" name=""><br>
<input type="hidden" name="raw_bytes" id="raw_bytes" />
<input type="submit" value="Upload" onclick="converttobyte()">
</form>
Django View:
def UploadFile(request):
if request.method == 'POST':
raw_bytes = request.POST['raw_bytes'].decode("base64")
I have a form that I want to be able to compare the numbers entered in two input boxes and if they match then I want to display a thumbs up image if they don't I want to display a thumbs down image. I'm attempting to use javascript to do this but I'm not sure how to get the images to display. I've searched this topic but am unable to find anything that explains how to display an image using javascript in the manner I need to do it.
Here is what I have for my code so far, and I'm not even sure if what I have is even correct,
if document.getElementById("scan_out").value == document.getElementById("scan_in").value
//do something here to display thumbs_up.png
else document.getElementById("scan_out").value >= document.getElementById("scan_in").value
//do something here to display thumbs_down.png
This is my first attempt at javascript so I'm not sure if I'm on the right track or not?
so this is what I have now as given from answers below
<html>
<head>
</head>
<body>
<form>
<input type="text" name="name" id="firstField"/>
<img src="images/thumbs_up.png" style="display: none;" id="image1"/>
<img src="images/thumbs_down.png" style="display:block;" id=image2"/>
<input type="text" name="name" id="secField" onchange="equals()"/>
</form>
</body>
<script type="text/javascript">
var firstField = document.getElementById('firstField');
var secField = document.getElementById('secField');
var image = document.getElementById('image2');
var image = document.getElementById('image1');
function equals() {
if(firstField.value == secField.value) {
image.style.display = 'block';
}
else {
image.style.display = 'none';
}
}
firstField.onkeyup = function() { equals() }
secField.onkeyup = function() { equals() }
</script>
but this always displays a thumbs down image then adds the thumbs up image if the inputs match showing both the thumbs up and thumbs down. I don't want there to be an image unless the values match or don't match but only after a value is input.
clean and easy way with js is following...
after edit
<html>
<head>
</head>
<body>
<form>
<input type="text" name="name" id="firstField"/>
<img src="images/thumbs_up.png" style="display: none; background: #000;" id="image"/>
<img src="images/thumbs_down.png" style="display: none; background: #ff0000;" id="image2"/>
<input type="text" name="name" id="secField" onchange="equals()"/>
</form>
</body>
<script type="text/javascript">
var firstField = document.getElementById('firstField');
var secField = document.getElementById('secField');
var image = document.getElementById('image');
var image2 = document.getElementById('image2');
function equals() {
if(firstField.value == secField.value) {
image.style.display = 'block';
image2.style.display = 'none';
}
else {
image.style.display = 'none';
image2.style.display = 'block';
}
}
firstField.onkeyup = equals;
secField.onkeyup = equals;
</script>
</html>
Here is an example how can you match numbers.
var n1 = parseInt(document.getElementById('text1').value, 10);
var n2 = parseInt(document.getElementById('text2').value, 10);
var l = document.querySelector('label');
if (n1 == n2)
l.innerHTML = 'Number1 = Number2';
else
l.innerHTML = 'Number1 != Number2';
If you are new to JavaScript, you shall definitely use jQuery.
Then the code would be:
if ( $("#scan_out").val() === $("#scan_in").val() ) {
$("#scan_icon").html('<img src="thumbs_up.png">');
} else {
$("#scan_icon").html('<img src="thumbs_down.png">');
}
You should place <div id="scan_icon"></div> where you want the icon to appear.
Create an empty div with id img1 and use this code
if( document.getElementById("scan_out").value == document.getElementById("scan_in").value)
{
document.getElementById("img1").innerHTML='<img src="path/to/image.png">';
}
else if( document.getElementById("scan_out").value >= document.getElementById("scan_in").value){
document.getElementById("img1").innerHTML='<img src="path/to/image2.png">';
}
if(document.getElementById("scan_out").value == document.getElementById("scan_in").value){
document.getElementById("img_id").src= "images/xyz/someimage.png";
}
else if(document.getElementById("scan_out").value == document.getElementById("scan_in").value){
document.getElementById("img_id1").src= "images/xyz/someimage.png";
}