Parse Cloud Code - Get URL of PFFile - javascript

Ok this should be a relatively simple one. Apologies i am an iOS developer usually trying to understand Javascript.
I have a PFFile that is being saves into a PFObject from iOS.
I now need to send the URL of the image to a web service, which i am trying to do using an afterSave method on Cloud Code.
I have the object being fetched, and i can see the file contained within it. But i can't work out how to access the URL value.
I have tried various approaches, and i'm sure it's me not understanding how to access the value on an object, nested in another object. I've listed what i mostly tried below.
I have everything else working apart from this so help would be greatly appreciated.
Thanks
Gareth
var image = request.object.get("userPhoto")
console.log(image);
var imageURL = image.url
var imageURL = image.'url'
var imageURL = image.(url)
var imageURL = image.('url')
console.log(imageURL);

The method for accessing the URL of the Parse.File object is:
var imageURL = image.url();
Per the docs here: https://parse.com/docs/js_guide#files-retrieving

Related

Expected full URL but got a child path, use ref instead

This is related to this thread, but it's a new problem I encountered. I am trying to add an image to a table cell in HTML, and I'm using Firebase Storage in combination with Firebase Database for this. The idea is to get the image from a gs://xxxxxxxx path in the database and use it in the js, but I get this error in the console:
Firebase Storage: Invalid argument in refFromURL at index 0: Expected full URL but got a child path, use ref instead."
So it seems that the url_ul path is not working. If, for example, I introduce the 'gs://xxxxxxxx' instead of url_ul, it works like a charm. And if I read the value url_ul as a text, I get that path. However, it doesn't work if I have that variable in refFromURL('url_ul')
I have the following js code for this:
var rootRef = firebase.database().ref().child("Test");
var storage = firebase.storage();
rootRef.on("child_added", snap => {
var headline = snap.child("headline").val();
var url_ul = snap.child("imageUrl").val();
var storageRef = storage.refFromURL('url_ul').then(function(url) {
var test = url;
document.querySelector('img').src = test;
}).catch(function(error) {});
$("#table_body").append("<tr><td>" + headline + "</td><td><img src='test' alt='' border=3 height=100 width=100></td></tr>");});
where the database looks like this:
So there is a gs://xxxxx path, which, according to Firebase documentation, should work fine:
// Create a reference from a Google Cloud Storage URI
var gsReference = storage.refFromURL('gs://bucket/images/stars.jpg')
Any idea what is wrong here?
To make things more clear:
This line works perfectly fine:
var storageRef = storage.refFromURL("gs://nameofapp.appspot.com/armonii_culturale.png").getDownloadURL().then(function(url) ...
But this one doesn't
var storageRef = storage.refFromURL("url_ul").getDownloadURL().then(function(url) ...
And it's strange because "url_ul" should contain the same value.

Extracting EXIF data (specifically dateTime and GPSLatitude and GPSLongitude) with JavaScript

I have a program where a camera is set up to constantly take pictures (about every 10 seconds or so) and the picture is sent to a folder on my server and then another program refreshes that folder constantly so that I always just have the most recent picture in that particular folder.
An HTML document exists that also constantly refreshes, and references that picture location to get and display the newest image.
What I'm trying to do is extract the EXIF data (that I've verified exists when I save the image from the active webpage and look at it's properties). I want to display the DateCreated (I believe this is DateTime) and the Latitude and Longitude (I believe is GPSLatitude and GPSLongitude).
I came across this library, exif-js, which seems like the go-to for most people trying to do this same thing in JavaScript. My code looks the same as the code at the bottom of the README.md file, except I changed out my img id="...." and variable names, (see below). It seems like it should work, but it's not producing any data. My empty span element just stays empty.
Is there an issue with the short time span that the page has before refreshing?
Thanks for any help!
Here's what my code currently looks like (just trying to get the DateTime info). I have also tried the GPSLatitude and GPSLongitude tags.
<!-- Library to extract EXIF data -->
<script src="vendors/exif-js/exif-js"></script>
<script type="text/javascript">
window.onload=getExif;
function getExif()
{
var img1 = document.getElementById("img1");
EXIF.getData(img1, function() {
var time = EXIF.getTag(this, "DateTime");
var img1Time = document.getElementById("img1Time");
img1Time.innerHTML = `${time}`;
});
var img2 = document.getElementById("img2");
EXIF.getData(img2, function() {
var allMetaData = EXIF.getALLTags(this);
var allMetaDataSpan = document.getElementById("Img2Time");
allMetaDataSpan.innerHTML = JSON.stringify(allMetaData, null, "\t");
});
}
</script>
go into ur exif.js file and then go to line 930 and then change it to
EXIF.getData = function(img, callback) {
if ((self.Image && img instanceof self.Image
|| self.HTMLImageElement && img instanceof self.HTMLImageElement)
&& !img.complete)
return false;
I know this may be already solved but I'd like to offer an alternative solution, for the people stumbling upon this question.
I'm a developer of a new library exifr you might want to try. It's maintained, actively developed library with focus on performance and works in both nodejs and browser.
async function getExif() {
let output = await exifr.parse(imgBuffer)
console.log('latitude', output.latitude) // converted by the library
console.log('longitude', output.longitude) // converted by the library
console.log('GPSLatitude', output.GPSLatitude) // raw value
console.log('GPSLongitude', output.GPSLongitude) // raw value
console.log('GPSDateStamp', output.GPSDateStamp)
console.log('DateTimeOriginal', output.DateTimeOriginal)
console.log('DateTimeDigitized', output.DateTimeDigitized)
console.log('ModifyDate', output.ModifyDate)
}
You can also try out the library's playground and experiment with images and their output, or check out the repository and docs.

Cannot Save Images from URL in Nativescript/Javascript with imageSource module

Context
I'm trying to download a users' Facebook profile picture to the local storage so that I can display it without having to remake the call to Facebook.
Code
I'm using the module image-source to download the image, and the module file-system to access the device's local storage.
Most of the code is referencing the Nativescript image-source documentation page.
var imageSource = require("image-source");
var fs = require("file-system");
exports.theFunction = function(args){
//...
var img = imageSource.fromFile("http://graph.facebook.com/"+user.id+"/picture?type=large");
var folder = fs.knownFolders.documents();
var path = fs.path.join(folder.path, "profilePic.jpg");
console.log(path);
var saved = img.saveToFile(path, enums.ImageFormat.jpg);
appSettings.setString("imgLocal",path);
console.log("Image Saved Successfully");
//...
}
Output
/data/user/0/com.foo.bar/files/profilePic.jpg
I never see the "Image Saved Successfully" message output to console and I have no way of verifying if the image has been stored in the filesystem using the Emulator (I'm developing for Android without a device).
I have also tried wrapping the save event in an if tag, assuming that the output of saveToFile() is a boolean:
if(img.saveToFile(path, enums.ImageFormat.jpg)) console.log("success");
else console.log("failure");
...however this also outputs nothing.
Question
How can I save the image from the URL to the device's local storage?
References
Nativescript
image-source on Nativescript docs
ImageSource on Nativescript API docs
I think main trouble here is in that line, cause ImageSource works only with local files, not urls:
var img = imageSource.fromFile("http://graph.facebook.com/"+user.id+"/picture?type=large");
You should download image, not set source from url. About downloading image you can read here:
https://docs.nativescript.org/cookbook/ui/image-cache
Or try something like this and save it than somehow:
var image = new ImageModule.Image();
image.src = "https://www.google.com/images/errors/logo_sm_2.png";
But about this I'm not quite sure. I've never used nativescript and just looked through the docs.

Javascript: how to append data to a file

how can i append data to a file using javascript?
i tried to use this code, but i got an error:
var fso = new ActiveXObject("Scripting.FileSystemOject");
var filepath = fso.GetFile("member.txt");
var fileObject = fso.OpenTextFile(filepath, 8);
file.WriteLine(id + "|" + pass);
fileObject.close();
the error is on var fso = new ActiveXObject("Scripting.FileSystemOject");, written: Error: Automation server can't create object
is there any other way to append the file using javascript or the way to fix this? thanks :)
EDIT:
i have doing what's written on this, and it still not working :/
I just realized these in your code:
var fileObject = fso.OpenTextFile(filepath, 8,true);
You'll need the true-argument, if the file does not exist, or you want to overwrite/append it.
var filepath = fso.GetFile("member.txt");// This won't work.
var filepath = "your_filePath"; // Use this instead
var fileObject = fso.OpenTextFile(filepath, 8, true);
OpenTextFile() needs a path as a string like "D:/test/file.txt". GetFile() returns an object, which you can see as a string (D:\test\file.txt), but it's not a string. Use also absolute paths, relative paths don't seem to work by my experience.
EDIT
Add the code below to the <head>-part of your html-file, then save locally as a hta (with file extension hta, not htm or html).
<hta:application
applicationName="MyApp"
id="myapp"
singleInstance="yes"
/>
Then run the hta-file. If you still getting an ActiveX-error, it's not supported by your OS. If this works, you haven't done all the security settings correct.
EDIT II
In this case it's not very usefull to get the path through ActiveX, you'll need to write it literal anyway. And I'm not supposed to do your homeworks, but this does the trick...
var filepath = new String(fso.GetFile("member.txt")).replace(/\\/g,'/');
And don't forget what I've said above about using absolute paths...
The 8 in the OpenTextFile function specify that you want to append to the file. Your problem comes from the security restriction of your browser. To make it work you'll have to lower the security level, which is not really recommended.
The error is thrown because there are security restrictions which donot allow the activex to run. change your security settings to allow the activex if your using internet explorer (which i think you are).
This might be useful http://windows.microsoft.com/en-US/windows/help/genuine/ie-activex
Cheers
EDIT: i have doing what's written on this, and it still not working :/
* try Restarting your browser
As pointed out in this comment
Javascript: how to append data to a file
the cause of the error Error: Automation server can't create object is the typo in the progid passed to ActiveXObject: Oject instead of Object:
var fso = new ActiveXObject("Scripting.FileSystemOject");
there is a missing b!

Reading image capture files in PhoneGap

I'm working on a PhoneGap application that captures images using the camera and, later, uploads them. There are two modes of operation for camera in PhoneGap: raw base64 encoded data or a file URI.
The docs themselves say:
Note: The image quality of pictures taken using the camera on newer
devices is quite good. Encoding such images using Base64 has caused
memory issues on some of these devices (iPhone 4, BlackBerry Torch
9800). Therefore, using FILE_URI as the 'Camera.destinationType' is
highly recommended.
So I'm keen to use FILE_URI option. This works great and you can even show the images in IMG tags. The URL looks like this:
file://localhost/var/mobile/Applications/4FE4642B-944C-449BB-9BD6-1E442E47C7CE/tmp/photo_047.jpg
However, at some point later I want to read the contents of the file to upload to a server. I was going to do this using the FileReader type. This doesn't work and I think it's because I can't access the file at the URL above.
The error code I get back from readDataUrl is 1 > FileError.NOT_FOUND_ERR = 1;
Any ideas how I can get to the file? I tried just accessing the last part of the path (photo_047.jpg) based on another sample I saw but no luck.
I'm just getting started with PhoneGap, and given the age of this question you may have found an answer already, but I'll give it a try anyway.
First, would you be able to use the built-in FileTransfer object? It takes a file: URI as an argument.
If FileTransfer won't work for you, and you need to read the file data yourself, you'll need the PhoneGap File objects, like FileReader , as you said. But most of those expect a plain pathname -- not a URI -- to specify the file to work with. The reason you're getting NOT_FOUND_ERR is because it's trying to open a file named file:/localhost/var....
Here's a quick one-liner to extract the path part from your URI:
var path = /file:\/\/.*?(\/.*)/.exec(fileuri)[1];
Hope this helps!
The answer from jgarbers was of help to me but it did not solve the problem. I realized the camera stores photos in Temp folder instead of Document folder. Setting my local file system to temporary allowed it to find the correct location for the camera images.
window.requestFileSystem(LocalFileSystem.TEMPORARY, 0, ...
...
window.requestFileSystem(LocalFileSystem.TEMPORARY, 0, ...
...
var path = /file://.?(/.)/.exec(fileuri)[1];
Ref. above jgarbers and Rik answers (solution has been tested successfully on iOs 7)
you can user the file transfer plugin for uploading any file to the server.
//// pass your file uri to the mediafie param
function uploadFile(mediaFile) {
var ft = new FileTransfer();
path = mediaFile.fullPath;
name = mediaFile.name;
////your service method url
var objUrl = http://example.com;
ft.upload(path,
objUrl,
function (result) {
alert("Success");
},
function (error) {
alert('Error uploading file ' + path + ': ' + error.code);
},
{ fileName: name });
}

Categories