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
Related
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>
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'm using jquery file upload to upload files to server side action. However, I would like to also send additional form fields as part of the form submit. Additionally, I want the formsubmit to happen only when the "submit" button is clicked.
Is this doable using jquery file upload?
I've created a jsbin: http://jsbin.com/mozujilede/1/edit?html,js,output
Desired behavior:
user should be alerted if they try to upload more files than allowed limit
additional form data should be sent to the server side along with multiple files
the form submit should happen only when user clicks submit button.
This is what I'm doing at the moment:
var maxFiles = 10;
$('#fileupload').fileupload({
singleFileUploads: false,
url: '/uploadUrl'
}).bind('fileuploadadd', function (e, data) {
var input = $('#input');
data.formData = {example: input.val()};
var fileCount = data.files.length;
if (fileCount > maxFiles) {
alert("The max number of files is "+maxFiles);
return false;
}
});
Try This
var byButton = false;
$("#sub-but").on("click",function(){
var inp = $("#files")[0];
if(inp.files.length > 10){
alert("Max number of files");
return false;
}
byButton = true;
$("#myForm").submit();
});
function validate(){
if(!byButton)
return false;
byButton = false;
return true;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myForm" onsubmit="return validate();">
<input type="text" placeholder="some extra items"/>
<input type="file" id="files" multiple="multiple"/>
<input type="button" value="Submit" id="sub-but"/>
</form>
I am trying to get an image loaded and displayed in a particular
slot depending on where I click, Say view1, view2 or view3 as shown below.
I have set up a form with div elements and I want to use ajax to
post and process a browsed image that I select using the
How can I pass the appropriate target: id name to the JavaScript to
display the image in the correct location? My scripts are shown below.
<form class = "ajaxform" method="post"
enctype = "multipart/form-data"
action = 'upload.php'>
<div id='view1' onclick="triggerFileUpload('photo')>view1</div>
<div id='view2' onclick="triggerFileUpload('photo')>view2</div>
<div id='view3' onclick="triggerFileUpload('photo')>view3</div>
<input type="file" name="imagefile" id="photo" />
</form>
<script type="text/javascript" >
$(document).ready(function() {
$('#photo').live('change', function() {
$(".ajaxform").ajaxForm({
target: '#view'
}).submit();
});
});
</script>
<script type="text/javascript">
function triggerFileUpload(f){
document.getElementById(f).click();
}
</script>
jsfiddle
You can attach events to the target divs using jQuery's click method and get the id from event.target.id. I'm not sure of the specifics of what you are trying to do, but I hope something along the lines of the following will suffice.
HTML
<form class = "ajaxform" method="post"
enctype = "multipart/form-data"
action = 'upload.php'>
<div id='view1' class='photo-target'>view1</div>
<div id='view2' class='photo-target'>view2</div>
<div id='view3' class='photo-target'>view3</div>
<input type="file" name="imagefile" id="photo" />
</form>
JavaScript
function createObjectURL(object) {
return (window.URL) ? window.URL.createObjectURL(object) : window.webkitURL.createObjectURL(object);
}
function revokeObjectURL(url) {
return (window.URL) ? window.URL.revokeObjectURL(url) : window.webkitURL.revokeObjectURL(url);
}
$(document).ready(function() {
var photoTarget = null;
$('#photo').on('change', function(event) {
var src = createObjectURL(this.files[0]);
var image = new Image();
image.src = src;
image.onload = function() {
revokeObjectURL(this.src);
};
$("#" + photoTarget).append(image);
$(".ajaxform").ajaxForm({
target: '#view'
}).submit();
});
$('.photo-target').click(function (event) {
photoTarget = event.target.id;
$("#photo").click();
});
});
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>