I am using the httpModule to call a dropbox rest service to download a text file. When I download it to internal storage it seems happy but then I cannot open the text file with the default app. So now I am pointing the download location to the external storage, but I am getting an error 'Error: Cannot save file with path: /storage/emulated/0/myNewDir'. I have added thee write_external_storage and read_external_storage permissions to the manifest. Here is my code:
HomePage.prototype.getFile = function() {
var filePath = fs.path.join(fs.knownFolders.currentApp().path, "myFile.txt");
storage.createDirectory("myNewDir");
httpModule.getFile({
url: "https://content.dropboxapi.com/2/files/download",
method: "POST",
headers: { "Content-Type": "",
"Dropbox-API-Arg": JSON.stringify({"path": "/path/file"}),
"Authorization": "*****" },
}, storage.buildAbsolutePath()+"/myNewDir").then(function (response) {
console.log(JSON.stringify(response));
}, function (e) {
console.log("Error occurred " + e);
});}
You need to specify the file name in the getFile function, like this:
httpModule.getFile({
url: "https://content.dropboxapi.com/2/files/download",
method: "POST",
headers: { "Content-Type": "",
"Dropbox-API-Arg": JSON.stringify({"path": "/path/file"}),
"Authorization": "*****" },
}, storage.buildAbsolutePath()+"/myNewDir/myFile.txt").then(function (response) {
console.log(JSON.stringify(response));
}, function (e) {
console.log("Error occurred " + e);
});}
Related
Sorry for the title, but i didn´t know how to explain it better. The thing is, i´m not getting any response from server-side and this is my code:
my .js file:
http.request({
url: "http://myPhpFile",
method: "POST",
headers: { "Content-Type": "application/json" },
content: JSON.stringify({ deviceToken: token, ambiente: platformModule.device.os })
}).then(function (response) {
console.log(response);
}, function (e) {
// console.log("Error occurred " + e);
})
my .php file:
<?php
$data = json_decode(file_get_contents('php://input'), true);
echo $data["deviceToken"];
?>
My console.log in my .js file doesn´t show anything in the terminal, what am i doing wrong?
Thanks, regards
I need to pass an sap.m.Image file to the body(Data) of an OData request. Below is the code and I would like to know what to pass to the data parameter of the request so that my Image gets uploaded to the backend. When I pass the ImgValue which contains the dataurl it gives out an error saying
DOMException: Failed to execute 'createElementNS' on 'Document': The qualified name provided ('d:0') contains the invalid name-start character
OData.request({
requestUri: "http://ambrifiori.am.brothergroup.net:8081/sap/opu/odata/sap/ZPVSYSTEM_SRV/PromoImagesSet/",
method: "POST",
headers: {
"X-Requested-With": "XMLHttpRequest",
"Content-Type": "application/atom+xml",
"DataServiceVersion": "2.0",
/*"Accept": "application/atom+xml,application/atomsvc+xml,application/xml", */
"X-CSRF-Token": header_xcsrf_token,
"slug": "ajay122",
},
data: ImgValue,
});
I wasn't able to post image data through OData hence I used ajax...
This is what I did.
OData.request
({
requestUri: "http://AMBRIFIORI.am.brothergroup.net:8081/sap/opu/odata/sap/ZUI5_DAILY_SALES_SRV/DailySalesSet",
method: "GET",
headers:
{
"X-Requested-With": "XMLHttpRequest",
"Content-Type": "application/atom+xml",
"DataServiceVersion": "2.0",
"X-CSRF-Token":"Fetch" }
},
function (data, response)
{
header_xcsrf_token = response.headers['x-csrf-token'];
csrftoken = header_xcsrf_token;
$.ajax({
url: 'http://ambrifiori.am.brothergroup.net:8081/sap/opu/odata/sap/ZPVSYSTEM_SRV/PromoImagesSet/',
//dataType: 'json',
data: imgData,
//data: image,
type: 'POST',
headers: { "X-Requested-With": "XMLHttpRequest",
"Content-Type": "image/png",
"DataServiceVersion": "2.0",
/*"Accept": "application/atom+xml,application/atomsvc+xml,application/xml", */
"X-CSRF-Token": csrftoken,
"slug": slug,
},
success: function(data) {
debugger;
console.log(data);
},
error: function(data) {
debugger;
console.log(data);
}
});
My ImgData consists of image in Data URI format base64. I just added one statement in my Imgvalue to convert it to ImgData which is
var imgData = JSON.stringify(ImgValue);
i'm working with Sharepoint-hosted apps with OData. I am trying to add attachment file to a list item after the item is created using its BdcIdentity but i am getting the error below:
{"readyState":4,"responseText":"{"error":{"code":"-2146232832,Microsoft.SharePoint.SPException","message":{"lang\":"en-US","value":"The List item must be saved to the content database before adding an attachment. To resolve this problem, save the list item and then add the attachment."}}}","status":500,"statusText":"Internal Server Error"}
Code to create the list item:
url: _spPageContextInfo.webAbsoluteUrl + "/_api/Web/Lists/GetByTitle('tbl_FeedbackDetails')/Items/",
type: "POST",
headers: {
"accept": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val(),
"content-Type": "application/json;odata=verbose"
},
data: JSON.stringify(details),
success.....
Below is my code after the item is created (im running this code inside the success function of the fist ajax call):
var queryUrl = _spPageContextInfo.webAbsoluteUrl + "/_api/lists/GetByTitle('ListName')/GetItemByStringId('BdcIdentity')/AttachmentFiles/add(FileName='filename')";
$.ajax({
url: queryUrl,
type: "POST",
processData: false,
contentType: "application/json;odata=verbose",
data: buffer,
headers: {
"accept": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val()
},
success: function (data) {
console.log(JSON.stringify(data));
console.log('Attachement Added Successfully');
},
error: function (error) {
console.log("Failure:" + error.status + "," + error.statusText);
console.log('Error full-text: ' + JSON.stringify(error));
}
});
The first call was successful in creating the list item. Am I doing things right?
I have the handleDownload method which starts a file download. The function posts to the backend, which gives back a response, based on that a new request posts to the server where the files are. I saw that I can use mockjax to mock the requests, but how to handle the different paths like success, error, etc. How should I know which response triggers which path (success,error, complete, ...). What would be a great startegy to test the handleDownload function, and how? For mocking I use Sinon.js I don't have a really deep understanding yet. I should also check either the handleDownloadFinal function is called.
handleDownload: function(data, url) {
$.ajax({
type: "POST",
url: url,
data: {},
success: function(response) {
if (response.success) {
var start_token = response.token;
$.ajax({
type: start_token.method,
url: start_token.url,
beforeSend: function(xhr) {
xhr.setRequestHeader('Authorization', start_token.header);
},
success: function(start_response) {
handleDownloadFinal(start_response.status_token);
},
error: function(start_response) {
$.ajax({
type: "POST",
url: url + 'proxy/',
success: function(fallback_response) {
if (fallback_response.success) {
handleDownloadFinal(fallback_response.status_token, true, fallback_response.job_uuid);
} else {
errorDownload(response.error);
}
},
error: function(fallback_response) {
// Now this is some real error
generalErrorDownload();
},
dataType: 'json'
});
},
dataType: 'json',
xhrFields: {
withCredentials: true
}
});
} else {
errorDownload(response.error);
}
},
error: function(response) {
generalErrorDownload();
},
complete: function() {
},
dataType: "json"
});
}
You should use the fake server coming with sinon.
before(function(){
//create the server
this.server = sinon.fakeServer.create();
// let the server automatically respond for every request
server.autoRespond = true;
})
it('test something', function(){
//let the server respond for specific url with 200-ok
this.server.respondWith("POST", "/some/article/comments.json", [200, {
"Content-Type": "application/json"
}, '[{ "id": 12, "comment": "Hey there" }]']);
})
As you have a bunch of requests and you have to check all combinations I would suggest to have helper function for every request fail success so you could test the cases like this:
function letFirstRequestSucceed() {
this.server.respondWith("POST", "urlForFirstRequest", [200, {
"Content-Type": "application/json"
}, '[{ "id": 12, "comment": "Hey there" }]']);
}
function letSecondRequestFail() {
this.server.respondWith("POST", "urlForSecondRequest", [404, {
"Content-Type": "application/json"
}, '{error: "some error message"}');
}
function letThirdRequestFail() {
this.server.respondWith("POST", "urlForThirdRequest", [404, {
"Content-Type": "application/json"
}, '{error: "some error message"}');
}
it("should to something when the second and third request fails", function () {
sinon.spy(window, 'generalErrorDownload');
letFirstRequestSucceed();
letSecondRequestFail();
letThirdRequestFail();
handleDownload('someDate', 'aUrl');
expect(generalErrorDownload)
})
Btw you should think about to refactor you code using jquerys deferred which is supported by api ajax calls, this would make your could much more readable.
I'm making an ajax request to retrieve json data from webtrends - a service that requires a login. I'm passing the username and password in my ajax request, but still gives me a 401 unauthorized error. I've tried 3 different methods - but no luck. Can someone pls help me find a solution?
1. $.getJSON('https://ws.webtrends.com/..?jsoncallback=?', { format: 'jsonp', suppress_error_codes: 'true', username: 'xxx', password: 'xxx', cache: 'false' }, function(json) {
console.log(json);
alert(json);
});
2. $.ajax({
url: "https://ws.webtrends.com/../?callback=?",
type: 'GET',
cache: false,
dataType: 'jsonp',
processData: false,
data: 'get=login',
username: "xxx",
password: "xxx",
beforeSend: function (req) {
req.setRequestHeader('Authorization', "xxx:xxx");
},
success: function (response) {
alert("success");
},
error: function(error) {
alert("error");
}
});
3. window.onload=function() {
var url = "https://ws.webtrends.com/...?username=xxx&password=xxx&callback=?";
var script = document.createElement('script');
script.setAttribute('src', url);
document.getElementsByTagName('head')[0].appendChild(script);
}
function parseRequest(response) {
try {
alert(response);
}
catch(an_exception) {
alert('error');
}
}
Method 3 might work when you use a named callback function and use basic authentication in the url. Mind though that a lot of browsers don't accept url-authentication (or whatever the name is). If you want to try it, you can rewrite it like this:
window.onload = function() {
var url = "https://xxx:xxx#ws.webtrends.com/...?callback=parseRequest";
var script = document.createElement('script');
script.setAttribute('src', url);
document.getElementsByTagName('head')[0].appendChild(script);
}
function parseRequest(response) {
try {
alert(response);
}
catch(an_exception) {
alert('error');
}
}