Get objectid of the uploaded image in parse - javascript

i'm trying to get the objectId of the image that i upload with PARSE Javascript.
With the following code im uploading successfuly the image to my parse app but also i'm trying to print out the object id of this uploaded image.
<!doctype html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script type="text/javascript" src="http://www.parsecdn.com/js/parse-latest.js"></script>
<script type="text/javascript">
$(document).ready(function() {
Parse.initialize("appid", "jskey");
function saveJobApp(objParseFile)
{
var jobApplication = new Parse.Object("magazia");
jobApplication.set("name", "Joe Smith");
jobApplication.set("image", objParseFile);
jobApplication.save(null,
{
success: function(gameScore) {
var photo = gameScore.get("image");
var name = gameScore.get("name");
var id = gameScore.get("objectId");
$("#profileImg")[0].src = photo.url();
$("#name")[0].innerHTML = name;
$("#objID")[0].innerHTML = id;
},
error: function(gameScore, error) {
alert('Failed to create new object, with error code: ' + error.description);
}
});
}
$('#profilePhotoFileUpload').bind("change", function(e) {
var fileUploadControl = $("#profilePhotoFileUpload")[0];
var file = fileUploadControl.files[0];
var name = file.name;
var parseFile = new Parse.File(name, file);
parseFile.save().then
(
function()
{
saveJobApp(parseFile);
},
function(error)
{
alert("error");
}
);
});
});
</script>
</head>
<body>
<input type="file" id="profilePhotoFileUpload">
<img id="profileImg"/>
<p id="name"></p>
<p id="objID"></p>
</body>
So i get the image and the name properly but i dont get the objectId and it says undefined.
Any idea?

Retrieving Object documentation from javaScript parse object you can use the following code :
var id = gameScore.id;
https://parse.com/docs/js/guide#objects-retrieving-objects
as you can see here it says exactly what you have to do with the data that parse itself makes to your class, such as objectId or time created and time updated. hope it helps.

Related

zip.js to read file name inside zip . (Client side scripting only)

have multiple file inputs in form now I have to check for each file input that zip file doesn't contain any invalid files (doc, docx and pdf only allow).
I wrote
<script src="https://code.jquery.com/jquery-2.2.1.js" integrity="sha256-eNcUzO3jsv0XlJLveFEkbB8bA7/CroNpNVk3XpmnwHc=" crossorigin="anonymous"></script>
<script type="text/javascript" src="/js/zip.js"/>
<script type="text/javascript" src="/js/inflate.js"/>
<script type="text/javascript" src="/js/deflate.js"/>
<script type="text/javascript" src="/js/z-worker.js"/>
<script type="text/javascript">
$(document).ready(function () {
if((window.location.href.indexOf("LibraryItemUpload`1&ParentId=7d428470-2234-41c0-85f4-a512d51198c6") > -1) || (window.location.href.indexOf("LibraryItemUpload%601&ParentId=7d428470-2234-41c0-85f4-a512d51198c6") > -1))
{
$("input:file").change(function () {
var regex=new RegExp("^[A-Za-z0-9 ]+$");
var file=this.files[0];
var key = this.value;
var ze = key.split('\\').pop();
var filename = ze.split('.')[0];
var extension=key.split('.').pop().trim().toLowerCase();
if(extension == 'zip')
{
zip.createReader(new zip.BlobReader(file), function(reader) {
// get all entries from the zip
reader.getEntries(function(entries) {
if (entries.length) {
// get first entry content as text
entries[0].getData(new zip.TextWriter(), function(text) {
// text contains the entry data as a String
console.log(text);
// close the zip reader
reader.close(function() {
// onclose callback
});
}, function(current, total) {
// onprogress callback
});
}
});
}, function(error) {
});
}
if (!regex.test(filename)) {
alert('Please do not use special characters in file name please rename file name and upload it again.');
location.reload();
}
else {
return true;
}
});
}
});
</script>
and written code to read file name from zip.js but flow doen't go in zip.createReader function.
please suggest me if another javascript available for read zip file, I just want entries object to read files name.
function readEntries(entries) {
var entryLength = entries.length;
for (i = 0; i < entryLength; i++) {
var entry = entries[i];
var fileName = entry.filename.substring(entry.filename.lastIndexOf("/") + 1); //if inside folder
var ext = fileName.split(".").pop().toLowerCase();
if (ext.toUpperCase() == 'DOC' || ext.toUpperCase() == 'PDF' ||
ext.toUpperCase() == 'DOCX') {
//logic
}
}
}
zip.useWebWorkers = false;//explicitly include (required) zip-workers ['zip.js','zip-fs.js','z-worker.js','inflate.js','deflate.js']
var fileInput = document.getElementById("zipfile");//Input File
fileInput.addEventListener('change', function(event) {
zip.createReader(new zip.BlobReader(fileInput.files[0]), function(zipReader) {
zipReader.getEntries(readEntries);
}, function (error) {
console.log(error);
});
});
I have not tested this piece of code, but I have used similar logic before.

Parse + Jquery uploading images

I'm creating my first website and I'm trying to create a user system. I've managed to upload images as files to parse, now I want to take it to the next level and let users crop the image before upload.
The problem is that you can't custom your input fields because of security issues. So I'd need a way to convert an image src to the "input:file" value to be able to submit it to parse. The following code is a snippet of my full code, however this is what is highlighted for this issue.
PS I am using cropit.( http://scottcheng.github.io/cropit/ )
HTML
<div class="form-group">
<div class="col-sm-10 col-sm-offset-2">
<label style="color:white; display:block;">Profile Picture:</label>
<img id="target" src="#" style="float:left; display:none;">
<div class="image-editor">
<input type="file" id="imageSubmit" class="cropit-image-input">
<div class="cropit-image-preview"></div>
<div class="image-size-label">
Resize image
</div>
<input type="range" class="cropit-image-zoom-input">
<button class="export" style="color:black">Export</button>
</div>
</div>
</div>
JS
$(function() {
$('.image-editor').cropit({
imageState: {
src: '',
},
});
$('.export').click(function() {
var imageData = $('.image-editor').cropit('export');
$('#target').toggle();
$('#target').attr('src', imageData);
$('.image-editor').toggle();
});
});
SIGNUP CODE
$scope.signUp = function(form){
// Upload image
var fileUploadControl = $("#imageSubmit")[0];
if (fileUploadControl.files.length > 0) {
var file = fileUploadControl.files[0];
var name = "displayPhoto.jpg";
var parseFile = new Parse.File(name, file);
}
parseFile.save().then(function() {
alert('success');
}, function(error) {
alert('fail');
});
var user = new Parse.User();
user.set("email", form.email);
user.set("username", form.username);
user.set("password", form.password);
user.set("picture", parseFile);
user.signUp(null, {
success: function(user){
$scope.scenario = '';
$scope.currentUser = user;
$scope.clearFields();
$scope.$apply();
},
error: function(user, error) {
$scope.displayError(true, error.message, error.code);
}
});
};
So I'd need the src from #target to be copied into the #imageSubmit input to be able to upload my file. I just can't find a way to do this.
Here's a fiddle for the whole experiment. (This opens the SRC in a new window, I've redirect it to an img tag, it's the image that pops up in a new window that I do want to save into parse)
https://jsfiddle.net/lilput/hfa6t6nj/2/
Very thankful for answers!! Cheers :)
SOLVED!!!! Thanks to Aaron Saunders
For anyone who has the same problem. All I did was to remove this whole chunk of code in my signup function:
// Upload image
var fileUploadControl = $("#imageSubmit")[0];
if (fileUploadControl.files.length > 0) {
var file = fileUploadControl.files[0];
var name = "displayPhoto.jpg";
var parseFile = new Parse.File(name, file);
}
parseFile.save().then(function() {
alert('success');
}, function(error) {
alert('fail');
});
And replaced it with this:
// Upload image
var file = new Parse.File("placeholder.txt", { base64: imageData });
file.save().then(function() {
alert('success');
}, function(error) {
alert('fail');
});
Upload the base64 image, I believe that is what you get back from the cropit plugin.
var file = new Parse.File("myfile.txt", { base64: imageData });

How to display image stored in variable using the url?

USING PARSE.COM AND THE JAVASCRIPT SDK
With the below code I can get as far as letting the user upload an image from the webpage and storing that as an object in a "file" column in the parse db.
I can store the image details, including the url in the
What i'm unable to do is extract the url back out and display the image on a html page.
I've added the screen shots to show how the data is held in var profilePhoto but i'm then unable to make it show on the page using $("profile_pic").attr('src',jobApplication[0]);
What have I overlooked ? I've searched SO and cannot find an relevant question that helps with this.
RESULTS IN INSPECT ELEMENT
Arguments[1]0: t.Filecallee: function () {length: 1__proto__: Object user_profile.html:408
t.File {_name: "tfss-fe809632-ffb8-445c-99f3-1149e4ffdec5-IMG_0047.jpg", _source:
t.Promise, _previousSave: t.Promise, _url:
"http://files.parsetfss.com/0fc5cba8-caf7-4c81-aafc…fe809632-ffb8-445c-99f3-1149e4ffdec5-IMG_0047.jpg",
name: function…}_name:
"tfss-fe809632-ffb8-445c-99f3-1149e4ffdec5-IMG_0047.jpg"_previousSave:
t.Promise_source: t.Promise_url:
"http://files.parsetfss.com/0fc5cba8-caf7-4c81-aafc-36390888e497/tfss-fe809632-ffb8-445c-99f3-1149e4ffdec5-IMG_0047.jpg"proto:
Object
CODE
$(document).ready(function() {
var parseAPPID = "XXX";
var parseJSID = "XXXX";
//Initialize Parse
Parse.initialize(parseAPPID,parseJSID);
$("#fileUploadBtn").on("click", function(e) {
var fileUploadControl = $("#fileUploader")[0];
if (fileUploadControl.files.length > 0) {
var file = fileUploadControl.files[0];
var name = file.name;
console.log("here goes nothing...");
var parseFile = new Parse.File(name, file);
parseFile.save().then(function() {
console.log("Woot!");
console.dir(arguments);
var User = Parse.Object.extend("_User")
var jobApplication = Parse.User.current();
jobApplication.set("ProfilePic", parseFile);
jobApplication.save();
var profilePhoto = jobApplication.get("ProfilePic");
console.log(profilePhoto);
$("profile_pic").attr('src',jobApplication[0]);
}, function(error) {
console.log("Error");
console.dir(error);
});
}
});
});
$("profile_pic") returns elements with profile_pic tag name, which obviously is not the thing you need. Don't see your HTML, but if profile_pic is id or class name of your img element, this will work if you type $("#profile_pic") or $(".profile_pic") respectively.

How to save an Image in Parse.com via JavaScript?

I wanna add new Object that containing an Image in one of its columns , but it dose not save My Pic , Is there any mistake in my code ? specially part of saving Image !!
My JavaScript where the problem appeared:
It never upload my pic in parse !!
<script type="text/javascript">
Parse.initialize("key", "key");
var products = Parse.Object.extend("products");
var fileUploadControl = $("#profilePhotoFileUpload")[0];
if (fileUploadControl.files.length > 0) {
var file = fileUploadControl.files[0];
var name = "photo.png";
var parseFile = new Parse.File(name, file);
}
parseFile.save().then(function() {
//The file has been saved to Parse.
}, function(error) {
// The file either could not be read, or could not be saved to Parse.
});
</script>
Here I added html line to upload file:
<input type="file" id="profilePhotoFileUpload">
I got the answer I am sharing it with you maybe someone get benefit
The THML line to upload file is:
<input type="file" id="pic">
The code in <script> to get and save image in parse is :
var fileUploadControl = $("#pic")[0];
if (fileUploadControl.files.length > 0) {
var file = fileUploadControl.files[0];
var name = "photo.png";
var parseFile = new Parse.File(name, file);
//put this inside if {
parseFile.save().then(function() {
// The file has been saved to Parse.
}, function(error) {
// The file either could not be read, or could not be saved to Parse.
});
// Be sure of ur parameters name
// prod is extend of my class in parse from this: var prod = new products();
prod.set("picture", parseFile);
prod.save();
}
Check the documentation here (at the end of that section, just before the one about retrieving files). Basically the issue is that like any other Parse object you need to save it first, then after the save is complete you can use it.
Create the file, save it, and in the save success handler you can then save the object with the reference to the file.
UPDATE: here's how your code above could be fixed:
Parse.initialize("key", "key");
var products = Parse.Object.extend("products");
var base64 = "V29ya2luZyBhdCBQYXJzZSBpcyBncmVhdCE=";
var file = new Parse.File("mypic.png", { base64: base64 });
file.save({
success: function(file) {
alert('File saved, now saving product with file reference...');
var prod = new products();
// to fill the columns
prod.set("productID", 1337);
prod.set("price", 10);
//I guess it need some fixing here
prod.set("picture", file);
prod.set("productName", "shampoo");
prod.set("productDescribe", "200 ml");
prod.save(null, {
success: function(prod) {
// Execute any logic that should take place after the object is saved.
alert('New object created with objectId: ' + prod.id);
},
error: function(error) {
// Execute any logic that should take place if the save fails.
// error is a Parse.Error with an error code and description.
alert('Failed to create new object, with error code: ' + error.description);
}
});
},
error: function(error) {
alert('Failed to save file: ' + error.description);
}
});

How do I upload an image using the Parse.com JavaScript SDK?

I'm using Parse.com to build a JavaScript app, and I need to upload photos. I have a form which allows users to select the image on their filesystem, but what do I do with it next? I can't find any documentation for this on the Parse site (not for the JavaScript SDK, anyway).
Here's a quick example on how to upload an image:
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script type="text/javascript" src="http://www.parsecdn.com/js/parse-1.2.15.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
// ***************************************************
// NOTE: Replace the following your own keys
// ***************************************************
Parse.initialize("YOUR_APPLICATION_ID", "YOUR_CLIENT_ID");
function saveJobApp(objParseFile)
{
var jobApplication = new Parse.Object("JobApplication");
jobApplication.set("applicantName", "Joe Smith");
jobApplication.set("profileImg", objParseFile);
jobApplication.save(null,
{
success: function(gameScore) {
// Execute any logic that should take place after the object is saved.
var photo = gameScore.get("profileImg");
$("#profileImg")[0].src = photo.url();
},
error: function(gameScore, error) {
// Execute any logic that should take place if the save fails.
// error is a Parse.Error with an error code and description.
alert('Failed to create new object, with error code: ' + error.description);
}
});
}
$('#profilePhotoFileUpload').bind("change", function(e) {
var fileUploadControl = $("#profilePhotoFileUpload")[0];
var file = fileUploadControl.files[0];
var name = file.name; //This does *NOT* need to be a unique name
var parseFile = new Parse.File(name, file);
parseFile.save().then
(
function()
{
saveJobApp(parseFile);
},
function(error)
{
alert("error");
}
);
});
});
</script>
<body>
<input type="file" id="profilePhotoFileUpload">
<img id="profileImg"/>
</body>

Categories

Resources