AngularJS upload photo without form submit - javascript

I want to upload a photo without hitting the having a submit button. I am using ionic framework and cordova plugin and the example below is getting a photo from the iphone's photo library.. for brevity i only included what's necessary for my request.
my view looks like this:
<form ng-submit="???">
<img class="img-circle" ng-src="{{prof_pic}}" ngclick="showActionsheet()" ng-if="pic_is_not_null()"/>
</form>
controller:
$scope.getPictureFromGallery = function() { $cordovaCamera.getPicture(secondoptions).then(function(imageData) {
$scope.imageData = imageData;
//data model
$scope.data = {prof_pic_link: imageData};
var image = angular.toJson($scope.data);
UserService.UpdateMyPhoto($localStorage.CurrentUser.id, $localStorage.CurrentUser.auth_token, image)
.success(function (data) {
$scope.prof_pic = "data:image/jpeg;base64," + imageData;
//to display the image in the view
}).
error(function(error,status) {
console.log(error);
console.log(status);
})
}, function(err) {
// error
});
};

You already have the answer in your question.
You can bind ng-click to a function that uploads the image to your server.
But more of a question is why you would not want the submit-button. Ponder this: The user whishes to upload an image, she selects an image that is to be uploaded but manages to select the wrong one.
If I read your scenario correctly, this will mean that the wrong image gets uploaded. If, on the other hand, there would be a submit-button the user can select a new image without the first one being uploaded.
So while you can do this, and you already have the answer yourself (ng-click="myUploadFunction(image)"), do you really want to?

Related

Update image rotator .xml config file without refresh

I have a 3D model being rendered on my site through an image rotator .xml config file. This feature works but I am attempting to render a completely different .xml in place of the previous file through a JS on change event.
I have done a fair bit of reading in order to solve this issue, although I have not found an answer. I have already tried to make the JQuery script into a function as seen below:
function updateModel(xml_file_path) {
console.log('updating room model...');
console.log('xml_file_path: ' + xml_file_path);
// clear past model
$("#wr360PlayerId").empty();
jQuery('#wr360PlayerId').rotator({
licenseFileURL: 'license.lic',
configFileURL: '/static/360_assets/' + xml_file_path,
graphicsPath: '/static/img/basic',
zIndexLayersOn: false,
responsiveBaseWidth: 600,
responsiveMinHeight: 0,
googleEventTracking: false,
});
console.log('rendering: ' + xml_file_path);
}
// clears the old model then updates the configFileURL to the new model
This was successful in clearing the previous model although when I inspect the new model the images used by the image rotator are not being loaded and nothing is displayed.
wr360 documentation
I've also read through the documentation for wr360 above and found a few different ways of loading the image rotator on my site. I've gone through each and attempted to make it update using similar methods as JQuery but each had their own oddities that were difficult to overcome.
There's not much to code to this as for most of it is created dynamically on page load, but I'll try to provide all code necessary below:
js
function updateModel(xml_file_path) {
console.log('updating room model...');
console.log('xml_file_path: ' + xml_file_path);
// clear past model
$("#wr360PlayerId").empty();
jQuery('#wr360PlayerId').rotator({
licenseFileURL: 'license.lic',
configFileURL: '/static/360_assets/' + xml_file_path,
graphicsPath: '/static/img/basic',
zIndexLayersOn: false,
responsiveBaseWidth: 600,
responsiveMinHeight: 0,
googleEventTracking: false,
});
console.log('rendering: ' + xml_file_path);
}
$(document).ready(function(){
$('#rooms').on('change', function() {
updateModel(room.xml_path);
console.log('model updated');
});
});
// truncated for simplicity
html
<div id="wr360PlayerId" class="wr360_player" style="background-color:#FFFFFF;">
</div>
The xml file path is getting passed correctly (checked by the console.log('xml_file_path: ' + xml_file_path);) it just doesn't render the second rotator.
$('#rooms') is a select field, and room.xml_path is the selected rooms .xml file path. With this being said, ideally, the on change event would show the selected model and if the selection changes again it should render the new model (instead of nothing like it currently does).
Either I am missing something or it is impossible to update a model without refreshing the page, either way, any help is appreciated!
You can actually use,
apiObj.reload(xml_path);
to simply reload the image rotator with a new xml file path.

Import file and submit when popup closes AngularJS

I am trying to submit the file I am importing once I click OK on system's window for uploading files, but i don't know how to do it... This is what I've done so far:
<input type="file" id="file-input" style="display:none" />
<button class="btn pull-right" ng-click="submitCashierFile()">Import</button>
JS:
$scope.submitCashierFile = function () {
angular.element('#file-input').trigger('click');
// I should have something like this next i guess?
$scope.cashierfile.upload = Upload.upload({
url: config.baseAddress + 'test/uploadCashierExcel',
data: { file: $scope.cashierfile }
});
$scope.cashierfile.upload.then(function (response) {
$timeout(function () {
$scope.cashierfile.result = response.data;
toastService.success('You have added .xlsx');
});
}, function (response) {
toastService.error(response);
});
};
So I triger the click, open the modal to choose file, the problem for me is how to submit it on clicking OK in that modal. Any suggestions?
Your question is not clear to me, but I will give it a shot base on what I did understand.
You should map the control's onchange event. This will fire right after selecting the file to upload.
Then you should do the actual upload of the file.
When I need to do this task, I drop use of Angular and go for HTML5 file upload mechanism. That one is working as you describe...

Cannot change src of image by JQuery

I am developing ASP.NET MVC 4 application. I am trying to change src attribute after controller sent data to a view, however all my attempts have no result. A script at a View:
<script type="text/javascript">
$(document).ready(function () {
$('#fileupload').fileupload({
dataType: 'json',
url: '/Home/UploadFiles',
autoUpload: true,
done: function (e, data) {
$('.file_name').html(data.result.name);
$('.file_type').html(data.result.type);
$('.file_size').html(data.result.size);
$('.file_source').attr('src', 'D:/somePhoto.jpg'); //this row does not set 'src' of <img/>
}
}).on('fileuploadprogressall', function (e, data) {
var progress = parseInt(data.loaded / data.total * 100, 10);
$('.progress .progress-bar').css('width', progress + '%');
});
});
</script>
<img class="file_source" src="" /> <!--src attribute is just empty--->
Could you tell please where I’ve made an error?
this row is not working:
$('.file_source').attr('src', 'D:/somePhoto.jpg'); //this row does not set 'src' of <img/>
The attribute 'src' of tag is not altered to src="D:/somePhoto.jpg".
Any help would be greatly appreciated.
Have you tried assigning a valid image location from the web inside the image source? I am pretty sure, D:\somePhoto.jpg is the location at server side. If that is the case, then javscript does not know how to get it, because js runs on client side, and after you have already sent the data from controller, there is nothing it could do.
First test with an image available from web to test, such as this - http://sci8.com/wp-content/uploads/2014/10/test-all-the-things.jpg
So change your code to -
$('.file_source').attr('src', 'http://sci8.com/wp-content/uploads/2014/10/test-all-the-things.jpg');
If that works ( and I am pretty sure, it will), then you know the reason why. Just keep the somePhoto.jpg somewhere inside the Content folder of your project and use that url.
for example
$('.file_source').attr('src', 'http://<hostaddress>/content/image/somePhoto.jpg');
If you are still facing problems, please let me know.

CollectionFS images not fully loading

I've just come across a werid problem, It seems my images are sometimes only loading slightly. Sometimes when I refresh the page manually they load fully but a lot of the time this happens - http://i.gyazo.com/a7050e430c79aa31ba557fc8271f1502.png
Not really sure why this is happening, I'm using collectionFS with cfs-ejson-file and cfs-s3 to store the images.
Here some example code ( main profile image )
Template code -
<div class="profile-avatar" style="height: 261px; margin-bottom: 30px;">
{{#if avatar }}
{{#if avatarReady }}
<img width="261px" height="261px" src="{{avatar.url}}" class="profile-avatar-img thumbnail" alt="Profile Image">
{{else}}
<div class="activity-spinner">
{{>spinner}}
</div>
{{/if}}
{{else}}
<img data-src="holder.js/100%x100%/text:No Profile Photo">
{{/if}}
</div> <!-- /.profile-avatar -->
Js code -
Template.profileLeft.helpers({
avatar: function(){
if(this.profile && this.profile.images)
return Images.findOne(this.profile.images[0]._id);
},
avatarReady: function(){
if(this.profile && this.profile.images){
var image = Images.findOne(this.profile.images[0]._id);
return image && image.isUploaded && image.hasStored("images");
}
},
});
I was seeing a similar problem to what you described. When I would upload an image and immediately display it, initially only a portion of it shows. I'll go into what I found and hopefully it helps.
I found that this was only happening when I would use a custom transformWrite: function in CollectionFS. What I believe is happening is there is a race condition causing the image.isUploaded() and image.hasStored() functions to return true before GraphicsMagick has finished writing the entire file. The partially processed image is then requested and cached by the web server. Like you said, sometimes when you refresh, the image will be then fully loaded.
As an example:
Your avatar URL that shows a partially processed image:
http://yourdomain.com/cfs/files/images/Bun5qheJDeaZDp5Mf/DSC_5498.JPG?&store=images
Add a fake query param to get around the cache, and the full image should be displayed:
http://yourdomain.com/cfs/files/images/Bun5qheJDeaZDp5Mf/DSC_5498.JPG?&store=images&bust=cache
What I ended up doing was setting an additional value on the model that was triggered whenever the image was finished processing. Below is an example of a gm function to process an image. Once the function is finished, another function is called "finishedProcessing" that sets the value on the model.
Sample Code:
gm(readStream, fileObj.name())
.resize(1000).quality(75)
.stream(function(err, stdout, stderr) {
if (err) {
return err;
}
stdout.pipe(writeStream);
// Update value when processing is finished
stdout.on('end', function(){
finishedProcessing(fileObj._id);
});
});
You can then grab the value of image.finishedProcessing before displaying the image:
avatarReady: function(){
if(this.profile && this.profile.images){
var image = Images.findOne(this.profile.images[0]._id);
return image && image.isUploaded() && image.hasStored("images") && image.finishedProcessing;
}
}
This seemed to work pretty well for me. Even if you're not using GraphicsMagick, there may be a similar condition that's happening when the file is being processed or saved.
Also, on a side note, I believe you need to call "image.isUploaded()" instead of "image.isUploaded" in your helper function to get the proper returned value.
UPDATE: On another another side note, I found that after refactoring if you do not have your collection settings set to Allow Update, then only the first chunk of the image will be saved and it can also cause the issue you are seeing.
Images.allow({
update: function(userId, file, fields, modifier) {
// This is to check whether or not CollectionFS is trying
// to update the Image
var validCFSUpdate = _.intersection(fields, ['chunkSize', 'chunkCount', 'chunkSize']).length > 0
// Only allow logged in users and CollectionFS to update the Image
return userId && validCFSUpdate;
}
});

Jquery Jcrop plugin loads image multiple times

I ran into an issue with jquery Jcrop plugin
I'm using it to allow the user to crop an image, but when he/she is not satisfied with that, I set to reset the original image.
I use PHP to store the original image and cropped the image as well.
When the user hits the reset button the original image loads from the server and jcrop is reapplied.
But dear friends my issue is when the user clicks the "reset image" button the cropped image and original image both are displaying. there is a new tag with no id or class is created by Jcrop and it doesn't remove when I destroy jcrop.
below is my code for the reset button
$("#reset_crop").click(function(){
refreshImg($("#profpic"), "files/"+fileName);
/*
refreshImg function adds date at Date() at the end of the image url to ignore cache. and change the src attr to the original file name.
*/
$(this).attr("disabled","disabled");
jcrop.destroy();
$("#profpic").on('load',function(){ jcrop = createJcrop(); });
});
My Jcrop settings are
function createJcrop(){
return $.Jcrop("#profpic",{
boxWidth:345,
trueSize:[width, height],
width:345,
onSelect: showCoords,
onChange: showCoords
});
}
the function of the crop button is
$("#crop").click(function(){
jcrop.release();
var newfile;
jcrop.destroy();
$.ajax({
url:'crop.php',
async:false,
data:{fileName:fileName,width:coordinates[0],height:coordinates[1],x:coordinates[2],y:coordinates[3]},
success:function(data){
//console.log(data);
newfile = data;
},
error:function(){
alert("something went wrong");
}
});
refreshImg($("#profpic"), "files/"+newfile);
$("#reset_crop").removeAttr('disabled');
$(this).attr("disabled","disabled");
});

Categories

Resources