Using file-input with accept image to access webcam on laptop - html

This most probably is a duplicate, please point me in the right direction:
I know how to use a file-upload input type=file with accept=image to allow fileupload of images from mobile devices.
<input type="file" name="myImage" accept="image/*" />
I would like to make this work on a Laptop just like on any other mobile device. Browser-Vendors still open up a Choose-File-Dialog where I would expect a "Choose-Source"-Dialog on mobile-devices.
I know that this is a thing that Browser-Vendors will have to solve, but in the meantime the question is: Is there any framework that emulates such a behaviour?

UPDATED ANSWER
<input type="file" accept="image/*" capture>
http://anssiko.github.io/html-media-capture/ for other media capture examples.
If you don't need IE support then you could try the MediaDevices.getUserMedia()
// A lot of other options are available - check out the constraints.
const constraints = { audio: true, video: { width: 1280, height: 720 } };
const video_stream = document.createElement('video');
navigator.mediaDevices.getUserMedia(constraints)
.then(function(mediaStream) {
video_stream.srcObject = mediaStream;
video_stream.onloadedmetadata = function(e) {
document.body.appendChild(video_stream);
video_stream.play();
};
})
.catch(function(err) { console.log(err.name + ": " + err.message); });
You can capture a frame and then append it to a canvas for preview and from there export it to .png/.jpg

Related

upload camera functionality doesn’t work on MS Teams task module on android

I have an extension in MS Teams, which open a task module - basically an angular application. as seen below:
The functionality of the app is to perform upload images.
HTML Code:
<input type="file" class="file-input" (change)="onFileSelected($event)" #fileUpload />
So, the issue is when I click the button on ios it gives me the option to upload from camera. But that’s not the case in android
After doing some research I tried a couple of options in HTML
<input accept="image/*" capture type="file" class="file-input" (change)="onFileSelected($event)" #cameraUpload />
or,
<input type="file" accept="image/*;capture=camera">
none of them works inside the teams.
Now when I run the app in the browser and click on file upload it shows the camera options:
How can I perform the same functionality inside MS Teams, task module
You can add below permissions to your manifest to support media capabilities:
"devicePermissions": [
"media"]
let imageProp: microsoftTeams.media.ImageProps = {
sources: [microsoftTeams.media.Source.Camera, microsoftTeams.media.Source.Gallery],
startMode: microsoftTeams.media.CameraStartMode.Photo,
ink: false,
cameraSwitcher: false,
textSticker: false,
enableFilter: true,
};
let mediaInput: microsoftTeams.media.MediaInputs = {
mediaType: microsoftTeams.media.MediaType.Image,
maxMediaCount: 10,
imageProps: imageProp
};
microsoftTeams.media.selectMedia(mediaInput, (error: microsoftTeams.SdkError, attachments: microsoftTeams.media.Media[]) => {
if (error) {
if (error.message) {
alert(" ErrorCode: " + error.errorCode + error.message);
} else {
alert(" ErrorCode: " + error.errorCode);
}
}
if (attachments) {
let y = attachments[0];
img.src = ("data:" + y.mimeType + ";base64," + y.preview); }
});
Can you please refer below documentation to integrate media capabilities.
https://learn.microsoft.com/en-us/microsoftteams/platform/concepts/device-capabilities/mobile-camera-image-permissions
Git Repo for sample code:
https://github.com/OfficeDev/Microsoft-Teams-Samples/tree/main/samples/tab-device-permissions/nodejs

form tag in html not posting/hitting website

so im trying to create a link shortener for me and my friend
to use on our small service center
but im having a small problem.
i set up an express server to get this done, whilst creating a fileuploader
which i used postman to test.
both work fine, but this is where im getting the problem.
whenever i use the snippet below to try and send data to the 'api'
it doesnt even post/touch the website yes i debugged to see if it touched
its only when i use form post/get method that the code doesnt work
HTML code snippet
<form method="POST" action="/shorten" enctype="application/x-www-form-urlencoded">
<label for="fUrl" class="sronly">URL</label>
<input class="input"
required
placeholder="URL"
type="url"
name="fUrl"
id="fUrl"
/>
<button type="submit">Shrink This!</button>
</form>
ive tried many things, i dont know if its because im rendering it with EJS or what
i tested it on its own with an HTML file but to no avail
if theres anything in this post i missed to go over let me know!
It looks like there is some issue with mapping between client and server. Try changing action value to the your API endpoint.
<form method="POST" action="http://myserver.com/shorten" enctype="application/x-www-form-urlencoded">
<label for="fUrl" class="sronly">URL</label>
<input class="input"
required
placeholder="URL"
type="url"
name="fUrl"
id="fUrl"
/>
<button type="submit">Shrink This!</button>
</form>
It was a problem of browsers being a tad too fast/slow
fix is here
// thanks to Vikasdeep Singh for this oddly specific url regex test
function isValidURL(string) {
var res = string.match(/(http(s)?:\/\/.)?(www\.)?[-a-zA-Z0-9#:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9#:%_\+.~#?&//=]*)/g);
return (res !== null)
};
var el = document.getElementById("yourButtonID");
el.addEventListener("click", avoidNSErrorWithFirefox, false); //Firefox
function avoidNSErrorWithFirefox() {
ElementInterval = setInterval(function() {
var url = document.getElementById("inputURL").value; // input tag
if (isValidURL(url)) {
var xhr = new XMLHttpRequest();
xhr.open("POST", "https://your-url.com/shorten", true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(JSON.stringify({
"url": url
}));
}
clearInterval(ElementInterval);
}, 0);
};
works like a charm on all browsers ive tested
edge chrome opera firefox
Hopefully me and my friends fix saves you some trouble with form / express problems!

Display image upload after page refresh

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 + "'>";
}
}

HTML file input — "accept" attribute not working

After reading through the comments on this post, I came up with the following syntax for the accept attribute:
Images
<input type="file" accept="image/jpeg, image/png, image/gif, .jpeg, .png, .gif">
Audio
<input type="file" accept="audio/mpeg, audio/x-wav, .mp3, .wav">
This works perfectly on desktop browsers, but does not appear to filter files at all on iOS or Android.
Are there any cross-browser solutions available?
I was unable to get the accept attribute to work for mobile. Ultimately I had to add an onchange handler to the input (general idea shown below).
Keep in mind, you'll still want to use the accept attribute as shown in my question, because it will work on desktop.
const supportedExtensions = ['jpeg', 'jpg', 'png', 'gif'];
const handleChange = ({ target }) => {
const path = target.value.split('.');
const extension = `${path[path.length - 1]}`;
if (supportedExtensions.includes(extension)) {
// TODO: upload
} else {
// TODO: show "invalid file type" message to user
// reset value
target.value = '';
}
}
The detail listing of browser support for "accept" attribute is listed in w3 schools. Have a look. It may help you.
I got the same problem, found this page, here is my workaround using onChange event.
I know this isn't true filtering and this is pretty ugly (I don't it), but it works indeed. I tested on my iOS and Android devices.
<script type="text/javascript">
let file;
function checkFile() {
file = document.querySelector('input[type=file]').files[0];
if (file.type != "image/png") {
file = null;
document.getElementById('image').remove();
let div = document.getElementById('div');
let image = document.createElement('input');
image.setAttribute('type', 'file');
image.setAttribute('id', 'image');
image.setAttribute('accept', 'image/png');
image.setAttribute('onchange', 'checkFile()');
div.appendChild(image);
window.alert('unsupported file type');
}
}
</script>
<div id="div">
<input type="file" id="image" accept="image/png" onchange="checkFile()">
</div>

How to allow <input type="file"> to accept only image files?

I need to upload only image file through <input type="file"> tag.
Right now, it accepts all file types. But, I want to restrict it to only specific image file extensions which include .jpg, .gif etc.
How can I achieve this functionality?
Use the accept attribute of the input tag. To accept only PNG's, JPEG's and GIF's you can use the following code:
<label>Your Image File
<input type="file" name="myImage" accept="image/png, image/gif, image/jpeg" />
</label>
Or simply:
<label>Your Image File
<input type="file" name="myImage" accept="image/*" />
</label>
Note that this only provides a hint to the browser as to what file-types to display to the user, but this can be easily circumvented, so you should always validate the uploaded file on the server also.
It should work in IE 10+, Chrome, Firefox, Safari 6+, Opera 15+, but support is very sketchy on mobiles (as of 2015) and by some reports, this may actually prevent some mobile browsers from uploading anything at all, so be sure to test your target platforms well.
For detailed browser support, see http://caniuse.com/#feat=input-file-accept
Using this:
<input type="file" accept="image/*">
works in both FF and Chrome.
Use it like this
<input type="file" accept=".png, .jpg, .jpeg" />
It worked for me
https://jsfiddle.net/ermagrawal/5u4ftp3k/
Steps:
1. Add accept attribute to input tag
2. Validate with javascript
3. Add server side validation to verify if the content is really an expected file type
For HTML and javascript:
<html>
<body>
<input name="image" type="file" id="fileName" accept=".jpg,.jpeg,.png" onchange="validateFileType()"/>
<script type="text/javascript">
function validateFileType(){
var fileName = document.getElementById("fileName").value;
var idxDot = fileName.lastIndexOf(".") + 1;
var extFile = fileName.substr(idxDot, fileName.length).toLowerCase();
if (extFile=="jpg" || extFile=="jpeg" || extFile=="png"){
//TO DO
}else{
alert("Only jpg/jpeg and png files are allowed!");
}
}
</script>
</body>
</html>
Explanation:
The accept attribute filters the files that will be displayed in the
file chooser popup. However, it is not a validation. It is only a
hint to the browser. The user can still change the options in the
popup.
The javascript only validates for file extension, but cannot
really verify if the select file is an actual jpg or png.
So you have to write for file content validation on server side.
This can be achieved by
<input type="file" accept="image/*" />
But this is not a good way. you have to code on the server side to check the file an image or not.
Check if image file is an actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
}
else {
echo "File is not an image.";
$uploadOk = 0;
}
}
For more reference, see here
http://www.w3schools.com/tags/att_input_accept.asp
http://www.w3schools.com/php/php_file_upload.asp
Using type="file" and accept="image/*" (or the format you want), allow the user to chose a file with specific format. But you have to re check it again in client side, because the user can select other type of files.
This works for me.
<input #imageInput accept="image/*" (change)="processFile(imageInput)" name="upload-photo" type="file" id="upload-photo" />
And then, in your javascript script
processFile(imageInput) {
if (imageInput.files[0]) {
const file: File = imageInput.files[0];
var pattern = /image-*/;
if (!file.type.match(pattern)) {
alert('Invalid format');
return;
}
// here you can do whatever you want with your image. Now you are sure that it is an image
}
}
Just as an addition: if you want to include all modern image file types with the best cross-browser support it should be:
<input type="file" accept="image/apng, image/avif, image/gif, image/jpeg, image/png, image/svg+xml, image/webp">
This allows all image file types that can be displayed in most browsers while excluding less commons formats like TIFF or formats that are not suitable for the web like PSD.
you can use accept attribute for <input type="file"> read this docs http://www.w3schools.com/tags/att_input_accept.asp
You can add specific type of image or other file type and do validation in your code :
<input style="margin-left: 10px; margin-top: 5px;" type="file" accept="image/x-png,image/jpeg,application/pdf"
(change)="handleFileInput($event,'creditRatingFile')" name="creditRatingFile" id="creditRatingFile">
handleFileInput(event) {
console.log(event);
const file = event.target.files[0];
if (file.size > 2097152) {
throw err;
} else if (
file.type !== "application/pdf" &&
file.type !== "application/wps-office.pdf" &&
file.type !== 'application/pdf' && file.type !== 'image/jpg' && file.type !== 'image/jpeg' && file.type !== "image/png"
) {
throw err;
} else {
console.log('file valid')
}
}
In html;
<input type="file" accept="image/*">
This will accept all image formats but no other file like pdf or video.
But if you are using django, in django forms.py;
image_field = forms.ImageField(Here_are_the_parameters)
If you want to upload multiple images at once you can add multiple attribute to input.
upload multiple files: <input type="file" multiple accept='image/*'>
Simple and powerful way(dynamic accept)
place formats in array like "image/*"
var upload=document.getElementById("upload");
var array=["video/mp4","image/png"];
upload.accept=array;
upload.addEventListener("change",()=>{
console.log(upload.value)
})
<input type="file" id="upload" >
Other people's answers refactored for ReactJS (hooks)
import React from 'react';
const ImageUploader = () => {
const handleImageUpload = (e) => {
// If no file selected, return
if (e.target.files.length === 0) return false;
const file = e.target.files[0];
// If no image selected, return
if (!/^image\//.test(file.type)) {
alert(`File ${file.name} is not an image.`);
return false;
}
// ...
};
return (
<>
<input type='file' accept='image/*' onChange={(e) => handleImageUpload(e)} />
</>
);
};
export default ImageUploader;