Create file on SkyDrive - javascript

I'm trying to create a new file on SkyDrive using JavaScript.
The closest thing I have so far is to create a file, but without any content.
function upload() {
WL.api({
path: "me/skydrive/files/testfile8.txt",
method: "PUT",
body: "Some file content"
}, function (response) {onError(response) });
function onError(response) {
$("#status").html(response.error)
}
}
Does anybody know how to create a new file on SkyDrive and pass a string as the file contents.
I have also tried using Ajax
$.ajax({
type : "PUT",
url: "https://apis.live.net/v5.0/me/skydrive/files/HelloWorld.txt?access_token=" + ACCESS_TOKEN,
data: "SOMEDATA",
processData: false,
success: function() { alert('Success!' );},
error: function(a,b,c) { alert('Error!' + a + b + c); }
});
This just returns a internal server error and leaves me pretty helpless :)
Anybody?

Sorry to reply to an old thread.
How about the following code?
It creates a file called 'hello.txt' that contains the string 'Hello, world!' in your SkyDrive folder.
var CLIENT_ID = '!!!!!!!!CLIENT ID!!!!!!!!';
var REDIRECT_URI = '!!!!!!!REDIRECT URI!!!!!!!';
var filename = 'hello.txt';
var content = 'Hello, world!';
var access_token = '';
WL.init({
client_id: CLIENT_ID,
redirect_uri: REDIRECT_URI
}).then(function (response) {
return WL.login({scope: ['wl.signin', 'wl.skydrive', 'wl.skydrive_update']});
}).then(function (response) {
access_token = response.session.access_token;
return WL.api({path: 'me/skydrive'});
}).then(function (response) {
var url = response.upload_location + filename + '?access_token=' + access_token;
var xhr = new XMLHttpRequest();
xhr.open('PUT', url);
xhr.onload = function () {
alert('success:', xhr.responseText);
};
xhr.onerror = function (error) {
alert('XHR error:', xhr.responseText);
};
xhr.send(new Blob([content]));
}, function (error) {
alert('error:', error);
});
BTW, This thread may also help you.

Related

sending json object to Django framework returns a 500 code error

I am sending an object using AJAX to a Django view. The data I am sending is mouse movement which is sent every 10 seconds to the server to be saved. Now, I have no problem reading my data from the client and server sides. The data gets saved in the database, but I get a 500 error message every time the function sends to the server gets executed. I tried to use fetch and got this error message:
POST error: SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON
I searched about this error, and my understanding is that the problem is with the data type, but I am unsure how I can trace the problem and fix it. Could someone help me troubleshoot this issue?
here is my js function:
var target_id = '';
var eventsLog = {"mouse": []};
function logMouse(event){
target_id = event.target.id;
currDate = new Date()
start_time = currDate.getHours() + ':' + currDate.getMinutes() + ':' + currDate.getSeconds() + ':' + currDate.getMilliseconds();
var insert = [start_time, target_id];
(eventsLog.mouse).push(insert);
}
var timesPerSecond = 5;
var wait = false;
$(document).on('mousemove', function (event) {
if (!wait) {
logMouse(event);
wait = true;
setTimeout(function () {
wait = false;
}, 1000 / timesPerSecond);
}
});
const post_url = server_url;
function sendMovement() {
/* fetch(post_url, {
method: 'POST',
body: JSON.stringify(eventsLog),
credentials: 'include',
headers: {'Content-Type': 'application/json'}
}).then(res => res.json()).then(response => {
console.log('POST response:', response);
}).catch(error => {
console.log('POST error:', error);
});*/
$.ajax({
type: "POST",
url: server_url,
contentType: "application/json; charset=utf-8",
data: JSON.stringify(eventsLog),
dataType: "json",
success: function () {
},
error: function (req, textStatus, errorThrown){
console.log('Ooops, something happened: ' + textStatus + ' ' +errorThrown)
}
});
and this is my Django view:
movement = json.loads(request.body.decode('utf-8'))
and I checked the data type received in Django and it is a dictionary.
Retrieve csrftoken from cookies and attach it on the request header. Use setInterval() to send the request every ten seconds. Of course you can implement with Fetch API, but since you were using jQuery on your movement function, I also used it to send an AJAX.
get_mouse_movement.html
(just the script part)
<script>
var target_id = '';
var eventsLog = {"mouse": []};
var timesPerSecond = 5;
var wait = false;
function getCookie(name) {
...
}
function logMouse(event){
target_id = event.target.id;
currDate = new Date()
start_time = currDate.getHours() + ':'
+ currDate.getMinutes() + ':'
+ currDate.getSeconds() + ':'
+ currDate.getMilliseconds();
console.log([start_time, target_id])
eventsLog.mouse.push([start_time, target_id]);
};
$(document).on('mousemove', function (event) {
if (!wait) {
logMouse(event);
wait = true;
setTimeout(function () {
wait = false;
}, 1000 / timesPerSecond);
}
});
function sendLog() {
$.ajax({
type: "POST",
url: '/your/url/',
headers: {'X-CSRFToken': getCookie('csrftoken'), 'Content-Type': 'application/json'},
data: JSON.stringify(eventsLog),
success: function(data) {
console.log(data.message);
eventsLog.mouse = [];
},
});
};
setInterval(function(){
sendLog();
}, 10000);
</script>
views.py
import json
from django.http import JsonResponse
def mouse_movement(request):
if request.method == 'POST':
data = json.loads(request.body)
print(data)
return JsonResponse({'message': 'log is saved'})
return render(request, 'get_mouse_movement.html')
.loads() accepts, str, bytes or bytearray. You do not need to decode it.

x-www-form-urlencoded post parameters (body) in frisby npm not working

I'm trying to test rest endpoint 'http://xxxxxxx/j_spring_security_check' to get authentication with frisby npm package.
I am able to work in postman, by selecting request body as 'x-www-form-urlencoded' tab and given my app credentials like key-value, its working fine as expected. But in frisby npm I am unable to set request body as 'x-www-form-urlencoded'.
I'm unable to login with this script.
Please help me in this or any other alternative suggestions would be great.
Here is my code:
var frisby7=require('frisby');
const qs = require('qs');
describe('API reference', function() {
var baseURL='http://xxxxxx/j_spring_security_check';
it('Simple Test with post url-encode form body request ', function() {
console.log("**********")
frisby7.globalSetup({
request: {
headers:{'Content-Type':'application/x-www-form-urlencoded'}
// headers: { 'X-Ms-Source':'api','X-Ms-Format':'xml','Authorization':'Basic c2hyZXlhIGdveWFsOm0jbWY4cDlMZ2ZAMU1xUTg='}
}
});
return frisby7.post(baseURL,
{
form: { j_username:'xxxx#xxxxx.com', j_password:'xxxx' }
}).then(function (res) { // res = FrisbyResponse object
console.log('status '+res.status);
console.log('body '+res.body);
//return res;
});
});
You are currently sending the object in the body as if you were using 'multipart/form-data'.
To send the request as 'application/x-www-form-urlencoded' you need to URI encode each property and then post them as a querystring
Try it like this
var objToSend = { j_username:'xxxx#xxxxx.com', j_password:'xxxx' };
var uriObj = Object.keys(objToSend).map(key => encodeURIComponent(key) + '=' + encodeURIComponent(objToSend[key])).join('&');
var url = baseURL + '?' + uriObj
frisby7.post(url);
Try something like this:
var frisby = require("frisby");
const Joi = frisby.Joi;
var req1 = {
method: "get",
url: "pass url here",
headers : {
"Accept": "application/json",
"content-type" : "application/json",
'Authorization': 'Basic ' + Buffer.from(username + ":" + password).toString('base64') // pass username and password for //validation
},
body: {}
};
describe('spec file name', function () {
it("spec file name" + dateTime, function(){
return frisby
.setup({ request: { headers : req1.headers } })
.get(req1.url)
.expect("status", 200)
.expect("header", "Content-Type", "application/json; charset=utf-8")
.expect("jsonTypes", {
"message": Joi.string()
})
.then(function(res) {
var body = res.body;
body = JSON.parse(body);
expect(body.message).toBeDefined();
})
.then(function(res) {
var body = res.body;
body = JSON.parse(body);
var req2 = {
method: "put",
url: "pass url here",
headers : {
"Accept": "application/json",
"content-type" : "application/json",
"Authorization": "JWT " + Token // anything that you using to authenticate
},
body: {}
};
return frisby
.setup({ request: { headers : req2.headers } })
.put(req2.url)
.expect("status", 200)
.expect("header", "content-type", "application/json; charset=utf-8")
.expect("jsonTypes", {
"message": Joi.string()
})
.then(function(res) {
var body = res.body;
body = JSON.parse(body);
expect(body.message).toBeDefined();
})
});
});
});

AJAX not uploading images to backend service

Working on a requirement to upload images to AWS instance. UI and service is separated and connects via REST. Service is in nodejs. from UI we are making a ajax call to backend service to upload the images to AWS.
The problem:
When I upload the images via POSTMAN request, I can see that response as uploaded with files properly uploaded in AWS.
Whereas when I upload images via AJAX call, I get no response in browser, and also the images are not uploaded in aws.
Below is the piece of code in ajax:
var formData = new FormData();
formData.append('image', $('#tx_file_programa')[0]);
$.ajax({
method: 'POST',
type: "POST",
url: 'http://10.0.0.95:9999/photo/1',
contentType: false,
processData: false,
async: false,
cache: false,
beforeSend: function (xhr) {
xhr.setRequestHeader('Authorization', 'Bearer ' + access_token );
},
data: formData,
success: function (data) {
console.log('response from server is : ', data);
}
//dataType: 'json'
});
This is the backend service.
server.post('/photo/:count', function (req, res) {
if (req.getContentType() == 'multipart/form-data') {
var form = new formidable.IncomingForm(),
files = [], fields = [];
var result = [];
var noOfFiles = req.params.count;
var count = 0;
console.log('noOfFiles', noOfFiles);
form.on('field', function(field, value) {
fields.push([field, value]);
console.log(fields);
})
form.on('progress', function(bytesReceived, bytesExpected) {
console.log('err');
});
form.on('error', function(err) {
console.log('err',err);
});
form.on('aborted', function() {
console.log('aborted', arguments);
});
new Promise(function(resolve, reject) {
var result = [];
form.onPart = function (part) {
var data = null;
const params = {
Bucket: 'xxxxx',
Key: uuidv4() + part.filename,
ACL: 'public-read'
};
var upload = s3Stream.upload(params);
upload.on('error', function (error) {
console.log('errr', error);
});
upload.on('part', function (details) {
console.log('part', details);
});
upload.on('uploaded', function (details) {
let extension = details.Location.split('.');
if(['JPG', 'PNG'].indexOf(extension[extension.length - 1].toUpperCase()) > -1) {
var ext = extension[extension.length - 1];
count++;
result.push(details.Location);
if(count == noOfFiles) {
resolve(result);
}
}
});
part.pipe(upload);
}
}).then(function(result){
console.log('end', result);
res.writeHead(200, {'content-type': 'text/plain'});
res.end('received files:\n\n ' + util.inspect(result));
})
form.parse(req, function (err, fields, files) {
})
return;
} else {
BadRequestResponse(res, "Invalid request type!");
}
})
#user3336194, Can you check with this, this is working thins
var appIconFormData = null
$(":file").change(function () {
var file = this.files[0], name = file.name, size = file.size, type = file.type;
var imageType = new Array("image/png", "image/jpeg", "image/gif", "image/bmp");
if (jQuery.inArray(type, imageType) == -1) {
return false;
} else {
appIconFormData = new FormData();
appIconFormData.append('appimage', $('input[type=file]')[0].files[0]);
}
});
$.ajax({
url: 'your/api/destination/url',
type: 'POST',
data: appIconFormData,
cache: false,
contentType: false,
processData: false,
success: function (data) {
console.log(data)
},
error: function (e) {
}
});
I think the way you are sending formdata is not correct.
Try these 2 ways:
You can give your whole form to FormData() for processing
var form = $('form')[0]; // You need to use standard javascript object here
var formData = new FormData(form);
or specify exact data for FormData()
var formData = new FormData();
// Attach file
formData.append('image', $('input[type=file]')[0].files[0]);

Angular JS methods - One depending on result of another

I have an AngularJS (v1.5) client that is used to schedule an Operating Room at a hospital. The app has a single controller and two functions within that controller. These two functions are both $http POST requests.
The first method called (requestAccessToken) passes a username, password, and grant_type to receive back an OAuth 2 access token which is then assigned to a variable on the scope. This works fine.
The second method (scheduleORSuite) makes an API call passing the access token obtained from the first method (requestAccessToken) . The problem is that when the method () executes the access token is null. I know I am receiving back a valid access token because when I call the method requestAccessToken directly I get back a valid access token. When I step through the debugger in Chrome it looks like the method (scheduleORSuite), that uses the access token, does not even wait for the method that obtains the access token to return.
<script type="text/javascript">
var scheduleORSuiteApp = angular.module('scheduleORSuiteApp', []);
scheduleORSuiteApp.controller('ScheduleORSuiteController', function ($scope, $http) {
var viewModel = this;
viewModel.accessToken = null;
viewModel.userName = 'theUserName';
viewModel.password = 'thePassword';
// This method requests the access token
viewModel.requestAccessToken = function () {
$http({
method : 'POST',
url: 'https://api.myserver.net/oauth/token',
data: 'username=' + viewModel.userName + '&password=' + viewModel.password + '&grant_type=password',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}).then(_requestAccessTokenSuccess, _requestAccessTokenError);
};
// This method contacts the API endpoint the schedule an OR suite
viewModel.scheduleORSuite = function() {
viewModel.requestAccessToken();
if (viewModel.accessToken) {
return; // viewModel.accessToken is null. Exit the method
}
$http({
method : 'POST',
url: 'https://api.myserver.net/api/scheduleOrSuite',
data : angular.toJson(viewModel.form),
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + viewModel.accessToken
}
}).then(_scheduleORSuiteSuccess, _scheduleORSuiteError);
};
// Called when request for access token is successful
function _requestAccessTokenSuccess(response) {
viewModel.tokenDisplay = response.data;
};
// Called when request for access token results in error
function _requestAccessTokenError(response) {
viewModel.tokenDisplay = 'An error occured: ' + response.status;
};
// Called when scheduling of operating suite is successful
function _scheduleORSuiteSuccess(response) {
viewModel.accessToken = response.data.access_token;
};
// Called when scheduling of operating suite results in error
function _scheduleORSuiteError(response) {
viewModel.tokenDisplay = 'An error occured: ' + response.data;
};
});
</script>
Here is the HTML form that makes use of the controller.
<form ng-submit="viewModel.scheduleORSuite()" novalidate>
...
...
</form>
Is there a way to make the second method (scheduleORSuite) wait until the first method (requestAccessToken) completes? The access token is required in order to call the API to schedule an OR suite.
$http is an async method, so you need to use callbacks
var scheduleORSuiteApp = angular.module('scheduleORSuiteApp', []);
scheduleORSuiteApp.controller('ScheduleORSuiteController', function($scope, $http) {
var viewModel = this;
viewModel.accessToken = null;
viewModel.userName = 'theUserName';
viewModel.password = 'thePassword';
viewModel.requestAccessToken = function() {
viewModel._requestAccessToken().then(_requestAccessTokenSuccess, _requestAccessTokenError);
};
viewModel.scheduleORSuite = function() {
if (viewModel.accessToken) {
viewModel._scheduleORSuite.then(_scheduleORSuiteSuccess, _scheduleORSuiteError);
} else {
viewModel._requestAccessToken().then(function(response) {
viewModel.tokenDisplay = response.data;
viewModel._scheduleORSuite.then(_scheduleORSuiteSuccess, _scheduleORSuiteError);
}, _requestAccessTokenError);
}
};
// This method contacts the API endpoint the schedule an OR suite
viewModel._scheduleORSuite = function() {
return $http({
method: 'POST',
url: 'https://api.myserver.net/api/scheduleOrSuite',
data: angular.toJson(viewModel.form),
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + viewModel.accessToken
}
});
};
// This method requests the access token
viewModel._requestAccessToken = function() {
return $http({
method: 'POST',
url: 'https://api.myserver.net/oauth/token',
data: 'username=' + viewModel.userName + '&password=' + viewModel.password + '&grant_type=password',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
})
};
// Called when request for access token is successful
function _requestAccessTokenSuccess(response) {
viewModel.tokenDisplay = response.data;
};
// Called when request for access token results in error
function _requestAccessTokenError(response) {
viewModel.tokenDisplay = 'An error occured: ' + response.status;
};
// Called when scheduling of operating suite is successful
function _scheduleORSuiteSuccess(response) {
viewModel.accessToken = response.data.access_token;
};
// Called when scheduling of operating suite results in error
function _scheduleORSuiteError(response) {
viewModel.tokenDisplay = 'An error occured: ' + response.data;
};
});
It's because your requestAccessToken() method contains a promise, and JavaScript won't wait for this to complete before carrying on with the rest of the code.
The best thing to do would be to return the promise from requestAccessToken() for use in scheduleORSuite()
viewModel.requestAccessToken = function () {
return $http({
method : 'POST',
url: 'https://api.myserver.net/oauth/token',
data: 'username=' + viewModel.userName + '&password=' + viewModel.password + '&grant_type=password',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
});
};
viewModel.scheduleORSuite = function() {
viewModel.requestAccessToken().then(function(response) {
viewModel._requestAccessTokenSuccess(response);
if (viewModel.accessToken) {
return; // viewModel.accessToken is null. Exit the method
}
$http({
method : 'POST',
url: 'https://api.myserver.net/api/scheduleOrSuite',
data : angular.toJson(viewModel.form),
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + viewModel.accessToken
}
}).then(_scheduleORSuiteSuccess, _scheduleORSuiteError);
}, _requestAccessTokenError);
};
I've also noticed though that the variable you're checking for your access token, viewModel.accesstoken, is being set until the _scheduleORSuiteSuccess() function? I'm presuming this is an error and it should be set in _requestAccessTokenSuccess() instead?
What you want todo is make sure the request returns with the access token first, then make the second request. Todo that, use a promise. the $q library works well for this. See viewModel.requestAccessTokenfor the changes I made.
<script type="text/javascript">
var scheduleORSuiteApp = angular.module('scheduleORSuiteApp', []);
scheduleORSuiteApp.controller('ScheduleORSuiteController', function($scope, $http, $q) {
var viewModel = this;
viewModel.accessToken = null;
viewModel.userName = 'theUserName';
viewModel.password = 'thePassword';
// This method requests the access token
viewModel.requestAccessToken = function() {
var defer = $q.defer();
$http({
method: 'POST',
url: 'https://api.myserver.net/oauth/token',
data: 'username=' + viewModel.userName + '&password=' + viewModel.password + '&grant_type=password',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}).then(function(response) {
viewModel.tokenDisplay = response.data;
defer.resolve(); //fullfills the promise
}, function(err) {
viewModel.tokenDisplay = 'An error occured: ' + response.status;
defer.reject(); //rejects the promise
});
return $q; //returns a promise
};
// This method contacts the API endpoint the schedule an OR suite
viewModel.scheduleORSuite = function() {
viewModel.requestAccessToken().then(function() {
//On fullfillment of the promise from requestAccessToken...
if (viewModel.accessToken) {
return; // viewModel.accessToken is null. Exit the method
}
$http({
method: 'POST',
url: 'https://api.myserver.net/api/scheduleOrSuite',
data: angular.toJson(viewModel.form),
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + viewModel.accessToken
}
}).then(_scheduleORSuiteSuccess, _scheduleORSuiteError);
}, function() {
//Error occured in requestAccessToken();
})
};
// Called when scheduling of operating suite is successful
function _scheduleORSuiteSuccess(response) {
viewModel.accessToken = response.data.access_token;
};
// Called when scheduling of operating suite results in error
function _scheduleORSuiteError(response) {
viewModel.tokenDisplay = 'An error occured: ' + response.data;
};
});
</script>

Clear Phonegap's InAppBrowser Cache

I am using Google authorization into my app. It works perfectly,
but the problem is cache not clear when someone logout from app.
I have tried adding clearcache=yes and clearsessioncache=yes, but they do not seem to do anything. Without clearing the cache when someone tries to log back in it validates the token with the previously signed in account.
Is there a way I can delete everything associated to the InAppBrowser ?
var googleapi = {
authorize: function (options) {
var deferred = $.Deferred();
//Build the OAuth consent page URL
var authUrl = 'https://accounts.google.com/o/oauth2/auth?' + $.param({
client_id: options.client_id,
redirect_uri: options.redirect_uri,
response_type: 'code',
scope: options.scope
});
var authWindow = window.open(authUrl,'_blank','location=no,toolbar=no,clearsessioncache=yes');
$(authWindow).on('loadstart', function (e) {
var url = e.originalEvent.url;
var code = /\?code=(.+)$/.exec(url);
var error = /\?error=(.+)$/.exec(url);
if (code || error) {
//Always close the browser when match is found
authWindow.close();
}
if (code) {
//Exchange the authorization code for an access token
$.post('https://accounts.google.com/o/oauth2/token', {
code: code[1],
client_id: options.client_id,
client_secret: options.client_secret,
redirect_uri: options.redirect_uri,
grant_type: 'authorization_code'
}).done(function (data) {
deferred.resolve(data);
$("#loginStatus").html('Name: ' + data.given_name);
}).fail(function (response) {
deferred.reject(response.responseJSON);
});
} else if (error) {
//The user denied access to the app
deferred.reject({
error: error[1]
});
}
});
return deferred.promise();
}
};
var accessToken;
var UserData = null;
function callGoogle() {
googleapi.authorize({
client_id: 'client_id',
client_secret: 'client_secret-key',
redirect_uri: 'http://localhost',
scope: 'https://www.googleapis.com/auth/plus.login https://www.googleapis.com/auth/userinfo.email'
}).done(function (data) {
accessToken = data.access_token;
getDataProfile();
});
}
function getDataProfile() {
var term = null;
$.ajax({
url: 'https://www.googleapis.com/oauth2/v1/userinfo?alt=json&access_token=' + accessToken,
type: 'GET',
data: term,
dataType: 'json',
error: function (jqXHR, text_status, strError) {
},
success: function (data) {
var item;
var OAuthToken = accessToken;
var OAuthAccessToken = data.id;
var username = data.email;
var firstname = data.given_name;
var lastname = data.family_name;
var ExternalIdentifier = data.id;
var Email = data.email;
var ProviderSystemName = "ExternalAuth.Google";
ExternalResponseInsert(apiSecretKey, storeId, languageId, username, firstname, lastname, Email, ExternalIdentifier, OAuthToken, OAuthAccessToken, ProviderSystemName);
}
});
//disconnectUser();
}
function disconnectUser() {
var revokeUrl = 'https://accounts.google.com/o/oauth2/revoke?token=' + accessToken;
$.ajax({
type: 'GET',
url: revokeUrl,
async: false,
contentType: "application/json",
dataType: 'jsonp',
success: function (nullResponse) {
accessToken = null;
console.log(JSON.stringify(nullResponse));
console.log("-----signed out..!!----" + accessToken);
},
error: function (e) {
// Handle the error
}
});
}

Categories

Resources