Reputation: 19
I want to upload images on click of img tag.When user Click on image, file input tag will call and user chose any image and set this image to clicked img tag.
How i will achive.Can anyone tell me.
Upvotes: 0
Views: 8638
Reputation: 2370
@shanks solution doesn't address setting the image to the clicked image. I have modified the code to address the same.
HTML
<input type="file" ng-file-select="uploadImage($files)" id="file-input" name="filedata"/>
<img src="no_image.png" ng-click="triggerUpload()" id="imageId"/>
JAVASCRIPT
In browsers supporting the File API, you can use the FileReader constructor to read files once they have been selected by the user. Supported browsers - IE 10+, Safari 6.0.2+, Chrome 7+, Firefox 3.6+, Opera 12.02+.
$scope.triggerUpload=function() {
var fileuploader = angular.element("#file-input");
fileuploader.on('click',function(){
console.log("File upload triggered programatically");
});
fileuploader.on('change', function(e) {
var reader = new FileReader();
reader.onload = function () {
document.getElementById('imageId').src = reader.result;
}
var files = fileuploader[0].files;
reader.readAsDataURL(files[0]);
});
fileuploader.trigger('click')
}
Uploading code is same as @shanks solution
$scope.uploadImage=function(selectedfiles)
{
$upload.upload({
url:"link to server script",
file:selectedFiles
})
}
Upvotes: 1
Reputation: 11
You can try ng-file-upload https://github.com/danialfarid/ng-file-upload
Use directive straight in img tag
Upvotes: 1
Reputation: 922
You can achieve this by triggering a click event with jquery. First thing to do is.
also get this angular module that makes file upload easy in angular
The HTML
<img src="no_image.png" ng-click="triggerUpload()" class="image-holder"/>
<input type="file" ng-file-select="uploadImage($files)" style="display:none" id="fileInput" name="filedata"/>
now to trigger the hidden file input control
THE JAVASCRIPT
$scope.triggerUpload=function()
{
var fileuploader = angular.element("#fileInput");
fileuploader.on('click',function(){
console.log("File upload triggered programatically");
})
fileuploader.trigger('click')
}
$scope.uploadImage=function(selectedfiles)
{
$upload.upload({
url:"link to server script",
file:selectedFiles
})
}
See this for a demo of the module
Upvotes: 2
Reputation: 3362
try this
<img url="#Your image url" alt="click here to add file upload" />
<div id="fileUpload" />
and script
$('img').click(function () {
AddFileUpload();
});
function AddFileUpload() {
$('#fileUpload').append('<input type="file"/>');
}
Upvotes: -1