html5 <input type="file" accept="image/*" capture="camera"> display as image rather than "choose file" button
You have to use Javascript Filereader for this. (Introduction into filereader-api: http://www.html5rocks.com/en/tutorials/file/dndfiles/)
Once the user have choose a image you can read the file-path of the chosen image and place it into your html.
Example:
<form id="form1" runat="server">
<input type='file' id="imgInp" />
<img id="blah" src="#" alt="your image" />
</form>
Javascript:
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#blah').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
$("#imgInp").change(function(){
readURL(this);
});
I know this is an old question but I came across it while trying to solve this same issue. I thought it'd be worth sharing this solution I hadn't found anywhere else.
Basically the solution is to use CSS to hide the <input>
element and style a <label>
around it to look like a button. Click the 'Run code snippet' button to see the results.
I had used a JavaScript solution before that worked fine too but it is nice to solve a 'presentation' issue with just CSS.
label.cameraButton {
display: inline-block;
margin: 1em 0;
/* Styles to make it look like a button */
padding: 0.5em;
border: 2px solid #666;
border-color: #EEE #CCC #CCC #EEE;
background-color: #DDD;
}
/* Look like a clicked/depressed button */
label.cameraButton:active {
border-color: #CCC #EEE #EEE #CCC;
}
/* This is the part that actually hides the 'Choose file' text box for camera inputs */
label.cameraButton input[accept*="camera"] {
display: none;
}
<!DOCTYPE html>
<html>
<head>
<title>Nice image capture button</title>
</head>
<body>
<label class="cameraButton">Take a picture
<input type="file" accept="image/*;capture=camera">
</label>
</body>
</html>
You can trigger a file input element by sending it a Javascript click event, e.g.
<input type="file" ... id="file-input">
$("#file-input").click();
You could put this in a click event handler for the image, for instance, then hide the file input with CSS. It'll still work even if it's invisible.
Once you've got that part working, you can set a change
event handler on the input element to see when the user puts a file into it. This event handler can create a temporary "blob" URL for the image by using window.URL.createObjectURL
, e.g.:
var file = document.getElementById("file-input").files[0];
var blob_url = window.URL.createObjectURL(file);
That URL can be set as the src
for an image on the page. (It only works on that page, though. Don't try to save it anywhere.)
Note that not all browsers currently support camera capture. (In fact, most desktop browsers don't.) Make sure your interface still makes sense if the user gets asked to pick a file.