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

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>

Related

Encoding a CSV file using javascript and passing the value to a 2nd Cloud Page not working as expected

What I am trying to do : I have a cloud page where the user can upload CSV file. When user clicks on the “upload” button the a function called getBase64() is called (please refer the below code). The getBase64() function will encode the uploaded file and post it to a second cloud page.The second cloud page then takes the posted data.
Note: I am trying to adapt this solution to my need (csv file) by referring to this article partially https://sfmarketing.cloud/2020/02/29/create-a-cloudpages-form-with-an-image-file-upload-option/
What’s the problem : When I try to click the the “upload” button the page is not taking me to the second CloudPage. Please could anyone let me know what I am doing wrong here ?
Here is the code:
CloudPage 1
<input id="file" type="file" accept=".csv">
<br>
<button id="button">Upload</button>
<script runat="client">
document.getElementById("button")
.addEventListener("click", function() {
var files = document.getElementById("file").files;
if (files.length > 0) {
getBase64(files[0]);
}
});
function getBase64(file) {
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function() {
//prepare data to pass to processing page
var fileEncoded = reader.result;
var base64enc = fileEncoded.split(";base64,")[1];
var fullFileName = document.getElementById("file").files[0].name;
var fileName = fullFileName.split(".")[0];
var assetName = fullFileName.split(".")[1];
fetch("https://cloud.link.example.com/PAGE2", { //provide URL of the processing page
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
base64enc: base64enc,
fileName: fileName,
assetName: assetName
})
})
.then(function(res) {
window.alert("Success!");
})
.catch(function(err) {
window.alert("Error!");
});
};
reader.onerror = function(error) {
console.log('Error: ', error);
};
}
</script>
CloudPage 2
<script runat="server">
var jsonData = Platform.Request.GetPostData();
var obj = Platform.Function.ParseJSON(jsonData);
</script>
I do not see any errors in the code and when I click on the upload button I get a success message but it does not take me to the second page. Please can anyone guide me how to retrieve this posted data in second page as I am not able to get the encoded data in page 2?

Get objectid of the uploaded image in parse

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.

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);
}
});

Code is giving error, "ReferenceError: CryptoJS is not defined" , while I have included required .js references, what's the reason?

Here is my code, I have included following .js files, onpage load it is giving error "ReferenceError: CryptoJS is not defined" why does it give that error when already js references are added. I am making a sharepoint-2013 app using office 365.
<script type="text/javascript" src="../Scripts/sha1.js"></script>
<script type="text/javascript" src="../Scripts/hmac-sha1.js"></script>
'use strict';
var context = SP.ClientContext.get_current();
var user = context.get_web().get_currentUser();
(function () {
// This code runs when the DOM is ready and creates a context object which is
// needed to use the SharePoint object model
$(document).ready(function ()
{
getUserName();
$("#button1").click(function()
{
paraupdate();
});
});
// This function prepares, loads, and then executes a SharePoint query to get
// the current users information
function paraupdate()
{
var str=""+$("#textbox1").val();
alert(""+str);
var message = str+"json539ff0f815ca697c681fe01d32ba52e3";
var secret = "<my private key>";
var crypto = CryptoJS.HmacSHA1(message, secret).toString();
alert("crypto answer is " + crypto);
var siteurl="http://pnrbuddy.com/api/station_by_code/code/"+str+"/format/json/pbapikey/539ff0f815ca697c681fe01d32ba52e3/pbapisign/"+crypto;
$.ajax({
url: siteurl,
type: "GET",
dataType: 'json',
success: function (data) {
alert("IN Success");
alert(""+data.station_by_code);
},
error: function (error) {
alert("IN Error");
alert(JSON.stringify(error));
}
});
}
function getUserName()
{
context.load(user);
context.executeQueryAsync(onGetUserNameSuccess, onGetUserNameFail);
}
// This function is executed if the above call is successful
// It replaces the contents of the 'message' element with the user name
function onGetUserNameSuccess()
{
$("#label1").html("Enter Station Code : ");
$("#button1").val("CLICK");
}
// This function is executed if the above call fails
function onGetUserNameFail(sender, args) {
alert('Failed to get user name. Error:' + args.get_message());
}
})();
include core-min.js before sha256.js
There are one of two forms for fixing this:
1: Manual Load, i have more success with this pattern:
$.getScript(scriptbase + "SP.Runtime.js",
function () {
$.getScript(scriptbase + "SP.js", execOperation);
}
);
Example:
$.getScript("~hostUrl/_layouts/15/SP.RequestExecutor.js", getListDataREST);
2: Script on Demand:
SP.SOD.executeFunc('sp.userprofiles.js', 'SP.ClientContext', loadUserData);
This SharepointExchange posting, gives the usual JSOM implementation for most AppParts: Jquery is not firing on Page load SharePoint 2013
Error solved I added online references instead,
<script src="http://crypto-js.googlecode.com/svn/tags/3.1.2/build/rollups/sha1.js"></script>
<script src="http://crypto-js.googlecode.com/svn/tags/3.1.2/build/rollups/hmac-sha1.js"></script>
Maybe is too late, but:
var CryptoJS = require('crypto-js');
var hash = CryptoJS.HmacSHA256("Message", "secret");
var hashInBase64 = CryptoJS.enc.Base64.stringify(hash);
console.log(hashInBase64); // qnR8UCqJggD55PohusaBNviGoOJ67HC6Btry4qXLVZc=
Works fine in node.js.

Upload an image with Phonegap: InvalidCastException

I am trying to upload a file to my server with Phonegap. I am currently stuck when an error that says:
InvalidCastException
Failed to deserialize WP7CordovaClassLib.Cordova.Commands.FileTransfer+UploadOptions[] with JSON value :: ["{\"filePath\":\"/CapturedImagesCache/PhotoChooser-51766419-c657-46db-a53d-f09bee300a89.jpg\",\"server\":\"http://server.myapp.srv.co.nz/pages/fileupload\",\"fileKey\":\"file\",\"fileName\":\"PhotoChooser-51766419-c657-46db-a53d-f09bee300a89.jpg\",\"mimeType\":\"image/jpg\",\"params\":\"value1=test&value2=param\",\"chunkedMode\":false}"]
The HTML + Javascript
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name="format-detection" content="telephone=no" />
<title>File Transfer Example</title>
</head>
<body>
<button id="uploadPhotoButton">Upload a Photo</button>
<script type="text/javascript" src="cordova-2.2.0.js"></script>
<script type="text/javascript" src="js/jquery-1.8.2.min.js"></script>
<script type="text/javascript" src="js/jquery.mobile-1.2.0.min.js"></script>
<script type="text/javascript" src="js/camera.js"></script>
<script type="text/javascript">
$(document).one("pause", function () {
console.log('Paused.');
});
$(document).one("resume", function () {
console.log('Resumed.');
});
$(document).one("deviceready", function () {
console.log('Device is ready.');
});
$(document).one("backbutton", function () {
console.log('Back button pressed.');
});
$(document).ready(function () {
console.log('DOM is ready.');
$(document).on("click", "#uploadPhotoButton", function (e) {
console.log('clicked button');
getImage();
});
function getImage() {
// Retrieve image file location from specified source
navigator.camera.getPicture(uploadPhoto, function (message) {
alert('get picture failed');
}, {
quality: 50,
destinationType: navigator.camera.DestinationType.FILE_URI,
sourceType: navigator.camera.PictureSourceType.PHOTOLIBRARY
}
);
}
function uploadPhoto(imageURI) {
var options = new FileUploadOptions();
options.fileKey = "file";
options.fileName = imageURI.substr(imageURI.lastIndexOf('/') + 1);
options.mimeType = "image/jpeg";
var params = new Object();
params.value1 = "test";
params.value2 = "param";
options.params = params;
options.chunkedMode = false;
var ft = new FileTransfer();
ft.upload(imageURI, "http://my.server.co.nz/pages/fileupload", win, fail, options);
}
function win(r) {
console.log("Code = " + r.responseCode);
console.log("Response = " + r.response);
console.log("Sent = " + r.bytesSent);
alert(r.response);
}
function fail(error) {
alert("An error has occurred: Code = " = error.code);
}
});
</script>
</body>
</html>
The complete error log.
GapBrowser_Navigated :: /app/www/index.html#/app/www/uploadtest.html
Log:"clicked button"
The thread '<No Name>' (0xf55026a) has exited with code 0 (0x0).
The thread '<No Name>' (0xe3f0326) has exited with code 0 (0x0).
INFO: AppDeactivated
INFO: AppActivated
Log:"Paused."
The thread '<No Name>' (0xf1a02e6) has exited with code 0 (0x0).
Log:"Resumed."
The thread '<No Name>' (0xf2a01d2) has exited with code 0 (0x0).
options = ["{\"filePath\":\"/CapturedImagesCache/PhotoChooser-51766419-c657-46db-a53d-f09bee300a89.jpg\",\"server\":\"http://my.server.co.nz/pages/fileupload\",\"fileKey\":\"file\",\"fileName\":\"PhotoChooser-51766419-c657-46db-a53d-f09bee300a89.jpg\",\"mimeType\":\"image/jpg\",\"params\":\"value1=test&value2=param\",\"chunkedMode\":false}"]
A first chance exception of type 'System.InvalidCastException' occurred in System.ServiceModel.Web.dll
A first chance exception of type 'System.InvalidCastException' occurred in System.ServiceModel.Web.dll
InvalidCastException
Failed to deserialize WP7CordovaClassLib.Cordova.Commands.FileTransfer+UploadOptions[] with JSON value :: ["{\"filePath\":\"/CapturedImagesCache/PhotoChooser-51766419-c657-46db-a53d-f09bee300a89.jpg\",\"server\":\"http://server.myapp.srv.co.nz/pages/fileupload\",\"fileKey\":\"file\",\"fileName\":\"PhotoChooser-51766419-c657-46db-a53d-f09bee300a89.jpg\",\"mimeType\":\"image/jpg\",\"params\":\"value1=test&value2=param\",\"chunkedMode\":false}"]
A first chance exception of type 'System.NullReferenceException' occurred in Lion.MyApp.dll
The thread '<No Name>' (0xfdc025e) has exited with code 0 (0x0).
Log:"Error in error callback: FileTransfer1325332352 = ReferenceError: Invalid left-hand side in assignment"
The thread '<No Name>' (0xfa60286) has exited with code 0 (0x0).
Does anyone have an idea on how to make this work?
Thanks!
W
I'm thinking that you are malforming your options value. Do you need to pass JSON or an actual object?
Right now you are passing an array with text in it.
options = ["{\"filePath\":\"/CapturedImagesCache/PhotoChooser-51766419-c657-46db-a53d-f09bee300a89.jpg\",\"server\":\"http://my.server.co.nz/pages/fileupload\",\"fileKey\":\"file\",\"fileName\":\"PhotoChooser-51766419-c657-46db-a53d-f09bee300a89.jpg\",\"mimeType\":\"image/jpg\",\"params\":\"value1=test&value2=param\",\"chunkedMode\":false}"]
The error seems to involve deserialization issues.
Put your getImage, uploadImage, win, fail outside of $(document).ready 's inline function call.
Reference to win and fail are actually closure, and phone gap gets it as null when it is trying to access those methods directly. Phonegap is probably expecting a global function instead of hidden function inside a function.
PhoneGap's executes its code out side javascript context, what may work in true javascript fashion may not work correctly with phonegap.
I had a problem similar to yours. I solved this, changing mimeType parameter to 'text/plain'.
Do you use params to send? If it's false I think you need send empty params.
I had this problem before, try to prepare the image in the html first, and dont take it directly from the navigator, it may not saving the taken photo in it cash ;)
In my solution I suppose to have an image tage with id ='camera_image'
img id='camera_image'...
Then i set all the variables of the image in it and I upload it (as you will see in the following code).
here's the 2 functions i used:
function takephoto(){
navigator.camera.getPicture(
function(uri){
$('#camera_image').show();
var img = document.getElementById('camera_image');
img.style.visibility = "visible";
img.style.display = "block";
img.src = uri;
uploadPhoto(img);
alert("Success");
},
function(e) {
console.log("Error getting picture: " + e);
},
{
quality: 50,
destinationType: navigator.camera.DestinationType.FILE_URI
});
// Get URI of picture to upload
var img = document.getElementById('camera_image');
var imageURI = img.src;
if (!imageURI || (img.style.display == "none")) {
alert("Take picture or select picture from library first.");
return;
}
}
for choosing an existing photo:
function choosephoto(){
navigator.camera.getPicture(
function(uri) {
$('#camera_image').show();
var img = document.getElementById('camera_image');
img.style.visibility = "visible";
img.style.display = "block";
img.src = uri;
uploadPhoto(img);
},
function(e) {
console.log("Error getting picture: " + e);
},
{
quality: 50,
destinationType: navigator.camera.DestinationType.FILE_URI,
sourceType: navigator.camera.PictureSourceType.SAVEDPHOTOALBUM
});
// Get URI of picture to upload
var img = document.getElementById('camera_image');
var imageURI = img.src;
if (!imageURI || (img.style.display == "none")) {
alert("please select a pic first");
return;
}
}
in the upload function:
function uploadPhoto(img) {
imageURI = img.src ...
ps: sorry for the formatting of my code, it doesn't fix well.

Categories

Resources