Angularjs upload service with onLoad image? - image

i have some issues with onload image and angular-fie-upload. first, i have to validate an image size after that i will upload this image to server side with the following code. my service look like that :
Services.factory('$uploadWrapper', ['$upload' , '$logger' , function ($upload, $logger) {
return function (url, file, informations, onSuccess, onError, onProgress) {
url = url || angular.noop;
file = file || angular.noop;
informations = informations || angular.noop;
onSuccess = onSuccess || angular.noop;
onError = onError || angular.noop;
onProgress = onProgress || angular.noop;
$upload.upload({
url: url,
method: 'POST',
// headers: {'header-key': 'header-value'},
// withCredentials: true,
data: informations,
file: file // or list of files: $files for html5 only
/* set the file formData name ('Content-Desposition'). Default is 'file' */
//fileFormDataName: myFile, //or a list of names for multiple files (html5).
/* customize how data is added to formData. See #40#issuecomment-28612000 for sample code */
//formDataAppender: function(formData, key, val){}
}).progress(function (evt) {
$logger.info(Math.min(100, parseInt(100.0 * evt.loaded / evt.total)));
onProgress(evt);
}).success(function (response) {
$logger.info('POST' + url + angular.toJson(response))
onSuccess(response);
}).error(function (error) {
$logger.error('POST' + url + ' ' + angular.toJson(error));
onError(error);
});
}
}]);
and for validation process, i will create an image to take the width and the height of my image :
$scope.onFileSelect = function ($files) {
$scope.loading = true;
//$files: an array of files selected, each file has name, size, and type.
file = $files[0];
var img = new Image();
img.src = _URL.createObjectURL(file);
img.onload = function () {
console.log(this.width + "x" + this.height);
if (img.width > sizes.width && img.height > sizes.height) {
$uploadWrapper(pinholeAdminServerRoutes.image.upload, file, {
"operationType": 'channels',
"objectId": $scope.channel.id,
"size": 'large'
}, function (response) {
$scope.loading = false;
}, function (error) {
$scope.errors.push(error);
$scope.loading = false;
});
} else {
$scope.imageSizeNotValid = true;
$scope.loading = false;
}
console.log('finish loading');
};
};
but, my service won't work inside the onload block. but the same service will work without the onload block.

i finally got a solution by using $scope.$apply inside the onload event.

Related

Worpress bad request 400 pure Javascript

I get this following error when I use ajax in pure javascript:
"POST http://localhost:8888/website/wp-admin/admin-ajax.php" 400 (Bad Request) line in code: this.xhr.send(JSON.stringify(data));
my Contact.js file:
var Contact = function(data){
//setups and others methods
this.onFormSent = function(data){
data = {
action: 'my_action',
data: data
};
if(this.ajaxSendURL !== null){
this.xhr.open("post", this.ajaxSendURL);
this.xhr.setRequestHeader("Content-Type", "application/json");
this.xhr.onload = function() {
if(self.xhr.status === 200){
console.log(self.xhr.responseText);
var response = JSON.parse(self.xhr.responseText);
self.onSuccessForm(data);
}
};
this.xhr.send(JSON.stringify(data));
}
};
};
I use a form tag in html after filled my "form" and pressed the submit button it should call 'my_action' in php.
this my function.php:
function add_theme_scripts() {
wp_enqueue_script('Contact', get_template_directory_uri() . '/js/Contact.js', array(), 1.0, true);
wp_localize_script('Contact', 'ajaxurl', admin_url('admin-ajax.php'));
}
add_action('wp_enqueue_scripts', 'add_theme_scripts');
/* AJAX */
add_action('wp_ajax_my_action', 'my_action');
add_action('wp_ajax_nopriv_my_action', 'my_action');
function my_action(){
echo 'msg from server:' + $_POST['data']['name'];
die();
}
What am I doing wrong?
Updated: replaced by the following code and it works
this.onFormSent = function(data){
data = "action=my_function&name=" + dada.name;
this.xhr.setRequestHeader("Content-Type", "application/json");
...
}
Change this lines in ajax request;
data = {
action: 'my_action',
data: youdatadata
};
var data = $.param(data);
http.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
http.send(data);

how to impletement a progressbar which shows me the uploading % with xhr function

let formData2 = new FormData();
formData2.append('_token', vm.response._token);
formData2.append('file', vm.response.content[i].path);
formData2.append('type', vm.response.content[i].type);
$.ajax({
async: false,
url: "page/file/create/upload/"+vm.response.topic_id,
type: "POST",
data: formData2,
cache: false,
dataType: 'json', // what to expect back from the PHP script
contentType: false,
processData: false,
xhr: function() {
var xhr = new XMLHttpRequest();
console.log(xhr);
xhr.open('POST', this.url, false);
if (xhr.open) {
console.log("xhr port open");
}
if (xhr.upload) {
xhr.upload.addEventListener('progress', this.onProgress);
console.log("xhr.upload");
}
return xhr;
// console.log(xhr);
},
success: function (title) {
console.log(" file upload in controller recieves: "+title);
},
})
}
point : 1 > this is a function written in "methods" in a vue page (file uploading practice project with laravel v5.5 + vue 1.0)
point : 2 > from my controller file is uploaded smoothly , has no issue with that.
point :3 > now i want to impletement a progressbar which shows me the uploading %
have tried xhr:function but do not know to fetch the uploading %...
now my xhr function is look like this.. if i get the value of percentage. i will bind that with my progressbar value. but i can not get any upload %
xhr: function() {
var xhr = jQuery.ajaxSettings.xhr();
console.log(xhr);
xhr.open('POST', this.url, false);
if (xhr.open) {
console.log("xhr port open");
}
if (xhr.upload) {
var percentage = 0;
xhr.upload.addEventListener('progress', function(e) {
if(e.lengthComputable) {
percentage = e.loaded/e.total;
percentage = parseInt(percentage * 100);
// Do what ever you want after here
console.log("percentage:"+percentage);
}
}, false);
}
return xhr;
// console.log(xhr);
},
You can try this code below, it works in my side:
xhr : function() {
var xhr = jQuery.ajaxSettings.xhr();
if(xhr.upload) {
if(xhr instanceof window.XMLHttpRequest) {
var percentage = 0;
xhr.upload.addEventListener('progress', function(e) {
if(e.lengthComputable) {
percentage = e.loaded/e.total;
percentage = parseInt(percentage * 100);
// Do what ever you want after here
}
}, false);
}
}
return xhr;
}
Basically, I was using xhr = jQuery.ajaxSettings.xhr() and xhr.upload.addEventListener progress to compute its progress percentage.
Hope this works.
Finally it's working for me. happy me :)
xhr: function () {
var xhr = new window.XMLHttpRequest();
xhr.upload.addEventListener("progress", function (evt) {
if (evt.lengthComputable) {
var percentComplete = evt.loaded / evt.total;
percentComplete = parseInt(percentComplete * 100);
console.log("% :" + percentComplete );
$('.myprogress').text(percentComplete + '%');
$('.myprogress').css('width', percentComplete + '%');
}
}, false);
return xhr;
},

ionic how to log http response in xcode

I am trying to upload an image to cloudinary using ionic cordova plugin. I can successfully post my image to cloudinary, but the response i received in xcode shows [object Object]. I would like to get the details of the response.
I tried printing the result using different ways such as iterating the keys of object, and nothing is been printed. is there a way for xcode to print out ionic console.log response? My code is as follow:
angular.module('starter.controllers', [])
.controller('DashCtrl', function($scope, $cordovaCamera, $cordovaGeolocation, $cordovaFileTransfer, $q, $base64, $translate) {
//$scope.$inject = ['$cordovaCamera','$cordovaGeolocation','$cordovaFileTransfer'];
$scope.imageURI = '';
$scope.log=function(){
console.log('hello~~~');
};
$scope.takePicture = function() {
console.log('taking pictures ....');
var uploadOptions = {
params : { 'upload_preset': "MY_PRESET"}
};
var options = {
quality: 50,
destinationType: Camera.DestinationType.FILE_URI,
sourceType: Camera.PictureSourceType.CAMERA,
encodingType: Camera.EncodingType.JPEG,
};
$cordovaCamera.getPicture(options).then(function(imageData) {
$scope.imageURI = imageData;
var ft = new FileTransfer();
function win (){
console.log('upload successful');
}
function fail(){
console.log('upload fail');
}
return $cordovaFileTransfer.upload("https://api.cloudinary.com/v1_1/MY_DOMAIN/image/upload", $scope.imageURI, uploadOptions);
})
.then(function(result){
console.log('result is~~~~~~ ', result);
console.log('print the result object '); // this shows nothing
var test1=JSON.parse(decodeURIComponent(result.response);
var test2=JSON.parse(decodeURIComponent(result);
console.log('test1 is ', test1); // didn't even print!!
console.log('test2 is ', test2); // didn't even print!!
for(var property in result[0]) {
console.log(property + "=" + obj[property]); // nothing here
}
for(var property in result[1]) {
console.log(property + "=" + obj[property]);// nothing here
}
for(var property in result) {
console.log(property + "=" + obj[property]);// nothing here
}
var url = result.secure_url || '';
var urlSmall;
if(result && result.eager[0]) { // this is not working
urlSmall = result.eager[0].secure_url || '';
console.log('url ~~~~~~~~ is ', urlSmall);
chat.sendMessage(roomId,'', 'default', urlSmall, function(result){
console.log('url is ', urlSmall);
console.log('message image url successfully updated to firebase');
})
}
// Do something with the results here.
$cordovaCamera.cleanup();
}, function(err){
// Do something with the error here
console.log('something is erroring')
$cordovaCamera.cleanup();
});
};
})

Sending Data to a Server using JavaScript (Firefox Addon)

I would like to send some data to an external server within an Firefox extension.
I tried this code snippet but it doesn’t work, due to Same-Origin-Policy.
$.ajax({
type: "POST",
url: 'https://127.0.0.1:54321',
data: ({foo: "bar"}),
crossDomain: true,
dataType: 'json'
}).done(function () {
alert("done");
}).fail(function(xhr, status, error) {
// var err = eval("(" + xhr.responseText + ")");
alert((xhr.responseText));
});
Since this does not work, I tried this tutorial:
https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
That got me this piece of code:
var invocation = new XMLHttpRequest(); var url = 'https://127.0.0.1:54321';
invocation.open('POST', url, true);
invocation.setRequestHeader('X-PINGOTHER', 'pingpong');
invocation.setRequestHeader('Content-Type', 'application/xml');
invocation.onreadystatechange = handler;
invocation.send(document.body);
This code also doesn't work and Firefox prompts that I should use CORS.
The weird thing is that it works if I don't use HTTPS (on non-HTTPS sites).
Note: On https://127.0.0.1:54321 runs a Java SSLServerSocket.
Copy paste this:
var {Cu, Cc, Ci} = require('chrome'); //addon-sdk way
//var {Cu: utils, Cc: classes, Ci: instances} = Components; //non addon-sdk
Cu.import('resource://gre/modules/Services.jsm');
function xhr(url, cb) {
let xhr = Cc["#mozilla.org/xmlextras/xmlhttprequest;1"].createInstance(Ci.nsIXMLHttpRequest);
let handler = ev => {
evf(m => xhr.removeEventListener(m, handler, !1));
switch (ev.type) {
case 'load':
if (xhr.status == 200) {
cb(xhr.response);
break;
}
default:
Services.prompt.alert(null, 'XHR Error', 'Error Fetching Package: ' + xhr.statusText + ' [' + ev.type + ':' + xhr.status + ']');
break;
}
};
let evf = f => ['load', 'error', 'abort'].forEach(f);
evf(m => xhr.addEventListener(m, handler, false));
xhr.mozBackgroundRequest = true;
xhr.open('GET', url, true);
xhr.channel.loadFlags |= Ci.nsIRequest.LOAD_ANONYMOUS | Ci.nsIRequest.LOAD_BYPASS_CACHE | Ci.nsIRequest.INHIBIT_PERSISTENT_CACHING;
//xhr.responseType = "arraybuffer"; //dont set it, so it returns string, you dont want arraybuffer. you only want this if your url is to a zip file or some file you want to download and make a nsIArrayBufferInputStream out of it or something
xhr.send(null);
}
xhr('https://www.gravatar.com/avatar/eb9895ade1bd6627e054429d1e18b576?s=24&d=identicon&r=PG&f=1', data => {
Services.prompt.alert(null, 'XHR Success', data);
var file = OS.Path.join(OS.Constants.Path.desktopDir, "test.png");
var promised = OS.File.writeAtomic(file, data);
promised.then(
function() {
alert('succesfully saved image to desktop')
},
function(ex) {
alert('FAILED in saving image to desktop')
}
);
});

Backbone collection fetch error with no information

I have a strange problem with the fetch of a backbone collection I am working with. In one particular instance of my code I perform a fetch (exactly how I do it in other areas of the code which all work fine), the fetch never seems to make it to the server and the developer tools shows the request as red with the word (canceled) in the status/text field.
I've walked this through into the backbone sync method and I see the $.ajax being built and everything looks fine. Has anyone run into this problem?
here is my code if it helps, this is a function that calls two .ashx services to first check for a file's existence then to open it. The part that isn't working for me is the "me.collection.fetch().
openDocument: function () {
var me = this,
fileId = me.model.get('id'),
userId = Dashboard.Data.Models.UserModel.get("UserInfo").User_ID,
fileRequest = '/genericHandlers/DownloadFile.ashx?id=' + fileId + '&userId=' + userId,
fileCheck = '/genericHandlers/CheckFileExistance.ashx?id=' + fileId + '&userId=' + userId;
//hide tooltip
me.hideButtonTooltips();
// Check for file existance
$.ajax({
url: fileCheck
})
.done(function (data) {
if (data && data === "true") {
document.location.href = fileRequest;
me.collection.fetch();
} else if (!!data && data === "false") {
"This file is no longer available.".notify('error');
}
})
.fail(function (data) {
"Something went wrong during the File Existance check".notify('error');
"Something went wrong during the File Existance check".log(userId, 'error', 'Docs');
});
},
my collection:
// docsCollection.js - The collection of ALL the documents available to a given user
// Document Collection
Dashboard.Collections.DocsCollection = Backbone.Collection.extend({
model: Dashboard.Models.DocumentUploadModel,
url: function () {
return 'apps/docs/Docs/' + this.userId;
},
initialize: function (options) {
this.userId = options.userId;
this.deferredFetch = this.fetch();
},
comparator: function (model) {
return -(new Date(model.get('expirationDate')));
},
getDaysSinceViewedDocuments: function () {
return this.filter(function (model) {
return model.get('daysSinceViewed') !== null;
});
},
getNewDocuments: function () {
return this.filter(function (model) {
return model.get('isNew');
});
},
getExpiredDocuments: function () {
return this.filter(function (model) {
return model.get('isExpired');
});
}
});
and my model:
Dashboard.Models.DocumentUploadModel = Backbone.Model.extend({
defaults: {
fileArray: [],
name: '',
description: '',
accesses: [],
tags: [],
expirationDate: ''
},
initialize: function () {
this.set({
userId: Dashboard.Data.Models.UserModel.get("UserInfo").User_ID,
expirationDate: (this.isNew()) ? buildExpirationDate() : this.get('expirationDate')
}, { silent: true });
function buildExpirationDate() {
var date = new Date((new Date()).getTime() + 24 * 60 * 60 * 1000 * 7),
dateString = "{0}/{1}/{2}".format(date.getMonth() + 1, date.getDate(), date.getFullYear());
return dateString;
}
},
firstFile: function () {
return this.get('fileArray')[0];
},
validate: function (attributes) {
var errors = [];
if (attributes.name === '' || attributes.name.length === 0)
errors.push({
input: 'input.txtName',
message: "You must enter a name."
});
if (attributes.description === '' || attributes.description.length === 0)
errors.push({
input: 'textarea.taDescription',
message: "You must enter a description."
});
if (errors.length > 0)
return errors;
return;
},
sync: function (method, model, options) {
var formData = new FormData(),
files = model.get("fileArray"),
$progress = $('progress'),
success = options.success,
error = options.error;
// Nothing other than create or update right now
if (method !== "create" && method !== "update")
return;
// Build formData object
formData.append("name", model.get("name"));
formData.append("description", model.get("description"));
formData.append("accesses", model.get("accesses"));
formData.append("tags", model.get("tags"));
formData.append("expirationDate", model.get("expirationDate"));
formData.append("userId", model.get("userId"));
formData.append("isNew", model.isNew());
// if not new then capture id
if (!model.isNew())
formData.append('id', model.id);
for (var i = 0; i < files.length; i++) {
formData.append('file', files[i]);
}
xhr = new XMLHttpRequest();
xhr.open('POST', '/genericHandlers/UploadDocsFile.ashx');
xhr.onload = function () {
if (xhr.status === 200) {
if (success)
success();
} else {
if (error)
error();
}
}
if ($progress.length > 0) {
xhr.upload.onprogress = function (evt) {
var complete;
if (evt.lengthComputable) {
// Do the division but if you cant put 0
complete = (evt.loaded / evt.total * 100 | 0);
$progress[0].value = $progress[0].innerHTML = complete;
}
}
}
xhr.send(formData);
},
upload: function (changedAttrs, options) {
this.save("create", changedAttrs, options);
}
});
You're assigning a value to document.location.href before you try to fetch your collection:
document.location.href = fileRequest;
me.collection.fetch();
Changing document.location.href will change the whole page and in the process, any currently running JavaScript will get shutdown so I wouldn't expect your me.collection.fetch() to ever get executed.

Resources