I am using titanium studio and i am trying to save am image from a POST request.
function buyImage(s){
var userName = Ti.App.Properties.getString('username');
var email = Ti.App.Properties.getString('email');
var encKey = Ti.App.Properties.getString('key');
var client = Ti.Network.createHTTPClient({
// function called when the response data is available
onload : function(e) {
Ti.API.info("Key Text: " + this.responseData);
Titanium.Media.saveToPhotoGallery(this.responseData,{
success: function(e) {
Titanium.UI.createAlertDialog({
title:'Photo Gallery',
message:'Check your photo gallery for you image'
}).show();
},
error: function(e) {
Titanium.UI.createAlertDialog({
title:'Error saving',
message:e.error
}).show();
}
});
Titanium.UI.createAlertDialog({title:'Photo Gallery',message:'Photo saved to gallery'}).show();
},
onerror : function(e) {
Ti.API.info(e.error);
alert('error');
},
timeout : 5000 // in milliseconds
});
// Prepare the connection.
client.open("POST", "http://somesite/create/save?userName="+userName+"&encryptionKey="+encKey+"&email="+email+"&recordId="+s);
// Send the request.
client.send();
The image says it saves ok and it says the responce data is a TiBlob but the image does not seem to save at all. When the same post is done in a post event in a browser you are prompted to download the image.
any ideas?
Related
I am new to Ajax Upload and use http://valums.com/ajax-upload js file to cater for my upload file function. As i try to click the button for ajax upload...the pop up window to select file is not showing so i was unable to select file. Below is my button and code to trigger ajax upload.
<button class="pbutton btn-glossy-black" id="browseFile">Browse</button>
var upload = new AjaxUpload('browseFile', {
action: jq_main_url + 'candidates/upload_attachment/' + main_folder_name,
name: 'upload_file',
data:{ 'countchecklist': 0},
onComplete: function(file, response) {
try {
var json = JSON.parse(response);
if(json.status == 'OK'){
alert('Complete');
} else {
core.jq_message(messageLevel, json.message);
}
} catch(e){
core.jq_message(messageLevel, e.message);
}
}
});
UPDATE: I failed to mention that I already read the suggested duplicate answer and it didn't get me any further as I didn't see how it related to my problem. The user ponury-kostek below, did however manage to explain it simply enough without all that clutter, for me to understand. So that's how I don't see it as a duplicate.
I'm trying to implement saving user data into a database when the user logs in with LinkedIn (to keep track of who watched my page). I found a tutorial that used jQuery, and I found a GitHub (here) page for conversion of jQuery to Vanilla JS, but I'm struggling to understand what I need to do to convert this specific statement.
I got the whole thing working using just that one line of jQuery, no problems - but I don't want to force users to load the jQuery lib!
I'll post the jQuery I'm trying to convert, the Vanilla JS solution I have so far, and the conversion "formula" suggested on the GitHub page:
jQuery I'm trying to convert:
$.post('saveUserData.php',
{
oauth_provider: 'linkedin',
userData: JSON.stringify(userData)
},
function(data){ return true; });
My attempt at a Vanilla JS solution
var theUrl = 'saveUserData.php';
var httpRequest = new XMLHttpRequest();
httpRequest.onreadystatechange = function (data) {
};
httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
httpRequest.open('POST', theUrl);
httpRequest.send({oauth_provider:'linkedin',userData: JSON.stringify(userData)}, function(data){ return true; });
Error thrown:
script.js:10 Uncaught DOMException: Failed to execute 'setRequestHeader' on 'XMLHttpRequest': The object's state must be OPENED.
at saveUserData (http://localhost:8012/linkedCV/script.js:10:14)
at displayProfileData (http://localhost:8012/linkedCV/index.php:43:4)
at B.<anonymous> (https://platform.linkedin.com/js/framework?v=1.0.350-1429&lang=undefined:3350:17)
at B.runHandler (https://platform.linkedin.com/js/framework?v=1.0.350-1429&lang=undefined:172:9)
at B.<anonymous> (https://platform.linkedin.com/js/framework?v=1.0.350-1429&lang=undefined:3355:6)
at B.handleSuccessResults (https://platform.linkedin.com/js/framework?v=1.0.350-1429&lang=undefined:172:9)
at Object.g [as success] (https://platform.linkedin.com/js/framework?v=1.0.350-1429&lang=undefined:3243:4)
at Object.incoming (https://platform.linkedin.com/js/framework?v=1.0.350-1429&lang=undefined:817:38)
at _window_onMessage (https://platform.linkedin.com/js/framework?v=1.0.350-1429&lang=undefined:581:102)
My JS (in the index header):
<script type="text/javascript" src="//platform.linkedin.com/in.js">
api_key: thecorrectAPIkey aka 'Client ID'
authorize: true
onLoad: onLinkedInLoad
scope: r_basicprofile r_emailaddress
</script>
<script type="text/javascript">
// Setup an event listener to make an API call once auth is complete
function onLinkedInLoad() {
IN.Event.on(IN, "auth", getProfileData);
}
// Use the API call wrapper to request the member's profile data
function getProfileData() {
IN.API.Profile("me").fields("id", "first-name", "last-name", "headline", "location", "picture-url", "public-profile-url", "email-address").result(displayProfileData).error(onError);
}
// Handle the successful return from the API call
function displayProfileData(data){
var user = data.values[0];
document.getElementById("picture").innerHTML = '<img src="'+user.pictureUrl+'" />';
document.getElementById("name").innerHTML = user.firstName+' '+user.lastName;
document.getElementById("intro").innerHTML = user.headline;
document.getElementById("email").innerHTML = user.emailAddress;
document.getElementById("location").innerHTML = user.location.name;
document.getElementById("link").innerHTML = 'Visit profile';
document.getElementById('profileData').style.display = 'block';
saveUserData(user);
}
// Handle an error response from the API call
function onError(error) {
console.log(error);
}
// Destroy the session of linkedin
function logout(){
IN.User.logout(removeProfileData);
}
// Remove profile data from page
function removeProfileData(){
document.getElementById('profileData').remove();
}
</script>
GitHub conversion suggestion:
// jQuery
$.post('//example.com', { username: username }, function (data) {
// code
})
// Vanilla
var httpRequest = new XMLHttpRequest()
httpRequest.onreadystatechange = function (data) {
// code
}
httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
httpRequest.open('POST', url)
httpRequest.send('username=' + encodeURIComponent(username))
Since this works perfectly as long as I use the suggested jQuery (the one I want to convert to Vanilla JS), it all works fine. So I'm going to assume the rest of the code of my page is not needed (the PHP for the DB connection and for saving user data to the DB).
https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/setRequestHeader
When using setRequestHeader(), you must call it after calling open(),
but before calling send().
var theUrl = 'saveUserData.php';
var httpRequest = new XMLHttpRequest();
httpRequest.onreadystatechange = function (data) {
};
httpRequest.open('POST', theUrl);
httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
httpRequest.send({oauth_provider:'linkedin',userData: JSON.stringify(userData)}, function(data){ return true; });
I have a problem saving an image in JSON. I can access the mobile camera using this code:
var pictureSource; // picture source
var destinationType; // sets the format of returned value
// Wait for PhoneGap to connect with the device
//
document.addEventListener("deviceready",onDeviceReady,false);
// PhoneGap is ready to be used!
//
function onDeviceReady() {
pictureSource=navigator.camera.PictureSourceType;
destinationType=navigator.camera.DestinationType;
}
function onPhotoFileSuccess(imageData) {
// Get image handle
console.log(JSON.stringify(imageData));
var smallImage = document.getElementById('smallImage');
smallImage.style.display = 'block';
smallImage.src = imageData;
location.href = "#pageone";
}
function capturePhotoWithFile() {
navigator.camera.getPicture(onPhotoFileSuccess, onFail, { quality: 50, destinationType: Camera.DestinationType.FILE_URI });
}
function onFail(message) {
alert('Failed because: ' + message);
}
My problem is that I have a form with text that should take and save a picture. This is my code that adds and saves the form without the image:
function Add(){
var client = JSON.stringify({
repairNum : $("#repairNum").val(),
fname : $("#fname").val(),
lname : $("#lname").val(),
address : $("#address").val(),
});
jewelryRepair.push(client);
localStorage.setItem("jewelryRepair", JSON.stringify(jewelryRepair));
alert("The data was saved.");
return true;
}
My question is, how can I insert the image file in this function add()? Thanks a lot!
Assuming that Add() gets called after onPhotoFileSuccess(), then you can do this in your Add() function (see below). It will be a data url - meaning the url has all of the image data encoded within it.
function Add(){
var client = JSON.stringify({
repairNum : $("#repairNum").val(),
fname : $("#fname").val(),
lname : $("#lname").val(),
address : $("#address").val(),
photoData: $("#smallImage").attr("src")
});
jewelryRepair.push(client);
localStorage.setItem("jewelryRepair", JSON.stringify(jewelryRepair));
alert("The data was saved.");
return true;
}
I am trying to download a PDF in my phonegap application and then immediately open it, but I get a File not Found error. It seems to download. Here is my code:
// Download
var url = "https://example/example.pdf";
var fileTransfer = new FileTransfer();
var uri = encodeURI(url);
var fileURL = 'cdvfile://localhost/persistent/com.mycompany.myApp/';
var fileName = 'example.pdf';
fileTransfer.download(
uri,
fileURL,
function (entry) {
alert("download complete: " + entry.fullPath);
// Open
cordova.plugins.fileOpener2.open(
fileURL + fileName,
'application/pdf',
{
error: function (errorObj) {
alert('Error status: ' + errorObj.status + ' - Error message: ' + errorObj.message + ' ' + errorObj.fileURL);
},
success: function () {
alert('file opened successfully');
}
}
);
},
function (error) {
alert("download error source " + error.source);
alert("download error target " + error.target);
alert("upload error code" + error.code);
}
);
alert('Downloading...');
I'm also wondering where is the best place to save files like this, that should be available after the app is closed?
second argument to fileTransfer.download is the location on device where you want to download pdf file.
You are setting var fileURL = 'cdvfile://localhost/persistent/com.mycompany.myApp/'; Which I believe does not exist. You can use file system plugin to first get file location on your device and then save it on device. you can use below code snapet.
var url = "https://example/example.pdf";
var uri = encodeURI(url);
//var fileURL = 'cdvfile://localhost/persistent/com.mycompany.myApp/';
// var fileName = 'example.pdf';
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFS, fail);
function gotFS(fileSystem) {
fileSystem.root.getDirectory("Dir_NAME", {
create: true,
exclusive: false
}, gotDirectory, fail);
}
function gotDirectory(entry) {
entry.getFile('yourFileNAme', {
create: true,
exclusive: false
}, gotFileEntry, fail);
}
function gotFileEntry(fileEntry) {
filePath = fileEntry.fullPath;
var fileTransfer = new FileTransfer();
fileTransfer.download(
'uri', filePath, function(entry) {
console.log("success");
//perform you launch task
}, function(error) {
console.log("error");
}, true, {});
}
I hope it will help you.
Even I am new to android but what I think that there is problem in URI
To open up a Uri in android it should have a structure like
file:///storage/....
(there should be 3 backslashes )
You can get more details here
The best place to save a pdf can be your sdcard or internal storage. Then the pdf will be available in your device even after the application closes.
If you wish to have the same pdf file, available in different devices while testing your application in different device/ or even in emulator you can save it in the assert folder of your android project.
hope this helps
I am working on a file uploader for my app and I settled on Filepicker.io. Everything is working fine except for one thing..When I upload an image to S3 I can only upload the URL that Filepicker returns (not the image itself).
The below is successful, but
Template.new_aphorism.events({
'change #attachment': function(event){
var savedFile = JSON.stringify(event.fpfile);
var parsedJSON = eval('('+savedFile+')');
var url=parsedJSON.url;
$('input[name=new_aphorism_image]').val(url);
console.log("saved file is:" + savedFile);
console.log(url);
filepicker.store(url, {location: 'S3'}, function(fpfile){
output.html('Uploaded: '+fpfile.filename+'');
}, function(fperror){
output.text(fperror.toString());
}, function(progress){
output.text("Uploading... ("+progress+"%)");
});
}
});
I get back as my message:
File stored in S3 at VnAa2YsOS6wOECNMWpwn_temp.txt and available at https://www.filepicker.io/api/file/vVtWTOl7QqOJ7gPmXkHQ
I have tried passing this and event.fpfile into my filepicker.store function but it just doesn't work.
Solved.
In the same function:
var file = event.fpfile;
filepicker.store(file, {location: 'S3'}, function(fpfile){