can't get Meteor slingshot to work - javascript

I am trying to get slingshot to work but having a hard time, I am attaching here the code I have.
The error I get n the console is:
"Exception in delivering result of invoking 'slingshot/uploadRequest': TypeError: Cannot read property 'response' of undefined"
client
Template.hello.events({
'change .uploadFile': function(event, template) {
event.preventDefault();
var uploader = new Slingshot.Upload("myFileUploads");
uploader.send(document.getElementById('uploadFile').files[0], function (error, downloadUrl) {
if (error) {
// Log service detailed response
console.error('Error uploading', uploader.xhr.response);
alert (error);
}
else{
console.log("Worked!");
}
});
}
});
lib
Slingshot.fileRestrictions("myFileUploads", {
allowedFileTypes: ["image/png", "image/jpeg", "image/gif"],
maxSize: null // 10 MB (use null for unlimited)
});
server
Slingshot.fileRestrictions("myFileUploads", {
allowedFileTypes: ["image/png", "image/jpeg", "image/gif"],
maxSize: null,
});
Slingshot.createDirective("myFileUploads", Slingshot.S3Storage, {
AWSAccessKeyId: "my-AWSAccessKeyId",
AWSSecretAccessKey: "my-AWSSecretAccessKey",
bucket: "slingshot-trial-2",
acl: "public-read",
authorize: function () {
//Deny uploads if user is not logged in.
},
key: function (file) {
//Store file into a directory by the user's username.
return file.name;
}
});

I saw the same issue and it was due to xhr being null - try removing the console error line that references it and I'm assuming you'll start seeing the alert with the actual error message:
console.error('Error uploading', uploader.xhr.response);
I ended up putting in a check for xhr before referencing it and then logging it if it existed.

Related

Google cloud 404 after verifying file exists

I have another project where this same code works successfully, so it may be some configuration option I've missed this time around. I'm using the google cloud API to access firebase storage.
For clarity, the file does exist.
var storage = require('#google-cloud/storage')({
keyFilename: 'serviceAccountKey.json',
projectId: 'my-id'
});
var bucket = storage.bucket('my-id.appspot.com');
var file = bucket.file('directory/file.json'); //this exists!
file.exists(function(err, exists){
console.log("Checking for challenges file. Results:" + exists + ", err:" + err); //returns "Checking for challenges file. Results:true, err:nil"
if (exists) {
console.log("File exists. Printing."); //prints "File exists. Printing."
file.download().then(function(currentFileData) {
console.log("This line is never reached.");
}).catch(err => {
console.error('ERROR:', err); //gives a 404 error
});
}
});
Instead of printing "this line is never reached.", it prints the following caught error:
ERROR: { ApiError: Not Found at Object.parseHttpRespMessage (/user_code/node_modules/#google-cloud/storage/node_modules/#google-cloud/common/src/util.js:156:33) at Object.handleResp ... ... The full error is colossal, so I won't post it here in its entirety unless required.
It's possible the user that is trying to access the file only have access over the bucket but not over the file. Check the ACLs of both the bucket and the file in both projects and compare what you get:
myBucket.acl.get()
.then(acls => console.log("Bucket ACLs:", acls));
myFile.acl.get()
.then(acls => console.log("File ACLs:", acls));
You should see an output like this:
[ [ { entity: 'user-abenavides333#gmail.com', role: 'OWNER' },
{ entity: 'user-dwilches#gmail.com', role: 'OWNER' } ],
{ kind: 'storage#objectAccessControls',
items: [ [Object], [Object] ] } ]
If there is no difference there, try the following more verbose versions of the same code:
myBucket.acl.get()
.then(acls => console.log("Bucket ACLs:", JSON.stringify(acls, null, '\t')));
myFile.acl.get()
.then(acls => console.log("File ACLs:", JSON.stringify(acls, null, '\t')));

Image File Download issue in ionic for iOS platform

I am trying to download some image files and store it for offline accessibility purpose of the app using Ionic framework. I have used two Cordova plugins named "Cordova-plugin-file" and "Cordova-plugin-file transfer". My code works on Android but faces a strange issue in iOS platform.
Error in Success callbackId: FileTransfer552364304 : TypeError: null
is not an object (evaluating 'result.lengthComputable'),
callbackFromNativecordova.js
Sometimes the code works, sometimes it throws me this error. Also I cannot access the error from my javascript code. Can anyone help? The code snippet is given below:
downloadImage: function(url, fileName) {
var deferred = $q.defer();
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fs) {
fs.root.getDirectory(
LOCAL_STORAGE_KEYS.app, {
create: true
},
function(dirEntry) {
// console.log(arguments);
dirEntry.getFile(
fileName, {
create: true,
exclusive: false
},
function(fe) {
console.log(arguments);
var p = fe.toURL();
console.log("In service the url path:", p);
fe.remove();
var ft = new FileTransfer();
console.log('File Transfer instance:',ft);
ft.download(
encodeURI(url),
p,
function(entry) {
console.log('In service the entry callback:',entry);
if (entry && entry.toURL) {
deferred.resolve(entry.toURL());
} else {
deferred.resolve();
}
},
function(err) {
console.log('Getting rejected:',err);
deferred.reject(err);
},
false,
null
);
},
function() {
deferred.reject(new Error('get file failed'));
}
);
}
);
},
function() {
deferred.reject(new Error('get directory failed'));
});
return deferred.promise;
}

Chrome Apps : How to save blob content to fileSystem in the background?

In Chrome Apps, I'm downloading a blob content from a server using JavaScript XHR (Angular $http GET in particular, with response type 'blob')
How should I save this to chrome application's file system?
Currently using an Angular wrapper on HTML5 filesystem API
https://github.com/maciel310/angular-filesystem
I do not want to show user a popup (hence I can't use chrome.fileSystem. chooseEntry )
The chrome.fileSystem.requestFileSystem API is only supported by Kiosk-only apps.
Hence I'm using HTML5 FileSystem API instead of chrome's.
I'm using following code to make XHR to fetch blob.
$http({
url: SERVER_URL+"/someVideo.mp4",
method: "GET",
responseType: "blob"
}).then(function(response) {
console.log(response);
fileSystem.writeBlob(response.name, response).then(function() {
console.log("file saved");
}, function(err) {
console.log(err);
});
}, function (response) {
});
This is my writeBlob method
writeBlob: function(fileName, blob, append) {
append = (typeof append == 'undefined' ? false : append);
var def = $q.defer();
fsDefer.promise.then(function(fs) {
fs.root.getFile(fileName, {create: true}, function(fileEntry) {
fileEntry.createWriter(function(fileWriter) {
if(append) {
fileWriter.seek(fileWriter.length);
}
var truncated = false;
fileWriter.onwriteend = function(e) {
//truncate all data after current position
if (!truncated) {
truncated = true;
this.truncate(this.position);
return;
}
safeResolve(def, "");
};
fileWriter.onerror = function(e) {
safeReject(def, {text: 'Write failed', obj: e});
};
fileWriter.write(blob);
}, function(e) {
safeReject(def, {text: "Error creating file", obj: e});
});
}, function(e) {
safeReject(def, {text: "Error getting file", obj: e});
});
}, function(err) {
def.reject(err);
});
return def.promise;
},
This shows SECURITY_ERR as It was determined that certain files are unsafe for access within a Web application, or that too many calls are being made on file resources.
What's the solution for this?
I've tried using --allow-file-access-from-files flag while launching app. It doesn't help.
Chrome Application's sandbox storage doesn't allow files to be stored in root directory (i.e. / )
Modify the code to save it in a specific sub-directory under it.
For example -
fileSystem.writeBlob("/new"+response.name, response).then(function() {
console.log("file saved");
}, function(err) {
console.log(err);
});
This would successfully save the file under /new/ directory.
To expand on this, here is a full example app on how to download a file and save the blob and display it back to the user.
https://github.com/PierBover/chrome-os-app-download-example

handle 503 error with jquery

I´m using gridfs to store images in a mongoDB. I have an issue when I update images in the background and want to update them on the screen when finished uploading. I fire an event when I have an image document stored in my mongoDB and then I update the screen. It looks like the document is created while uploading the image because if I do it this way, my image is broken with a 503 error (service not available). When I refresh the page the image appears on the screen.
I believe the problem is that I try to get the image when it is still uploading. I would like to do a $.get(imagesURL) and catch the 503 error but I don't know how to do this. If I could catch the error I could do a loop and wait until its uploaded.
Maybe you guys also have better solutions or know how to catch a 503 error using jquery?
I use a normal file input field for the image
(part of my Template Event in meteorjs)
'change #avatarForm': function (event) {
FS.Utility.eachFile(event, function (file) {
Images.insert(file, function (err, fileObj) {
if (err) {
// handle error
} else {
// handle success depending what you need to do
var userId = Meteor.userId();
var imagesURL = {
"profile.image": "/cfs/files/images/" + fileObj._id
};
Meteor.users.update(userId, {$set: imagesURL});
function checkAvatar() {
$.get(imagesURL)
.complete(function () {
Session.set("registerAvatar", "/cfs/files/images/" + fileObj._id);
}).onerror(function () {
console.log("but still uploading");
checkAvatar();
});
console.log("image saved!");
}
checkAvatar();
}
});
});
},
my code should only fire the new image on the screen (url is set as SessionVar) when the image is completed but its not working.
this is my exact error
Failed to load resource: the server responded with a status of 503 (Service Unavailable)
Something like this should work. The pattern is to set a template helper with a reactive data source - in this case, Meteor.user(). When Meteor.user() changes, the template helper will render out the new data without you having to fetch any data manually:
<template name="test">
<div>Profile Image:</div>
{{#if profileImage}}
<div><img src="{{profileImage}}"></div>
{{/if}}
</template>
Template.test.events({
'change #avatarForm': function(event) {
FS.Utility.eachFile(event, function(file) {
Images.insert(file, function(err, fileObj) {
if (err) {
// handle error
} else {
// handle success depending what you need to do
var userId = Meteor.userId();
var profileImage = {
"profile.image.url": fileObj.url(),
"profile.image.id": fileObj._id
};
Meteor.users.update(userId, {
$set: profileImage
});
}
});
});
},
});
Template.test.helpers({
profileImage: function () {
return Meteor.user().profile.image.url;
}
});

Template.meteorError.rendered doesn't work in errors meteor package

I am trying to use meteor-errors package in my meteor project.
It has two main files with javascript code:
errors_list.js:
Template.meteorErrors.helpers({
errors: function() {
return Errors.collection.find();
}
});
Template.meteorError.rendered = function() {
var error = this.data;
Meteor.defer(function() {
Errors.collection.update(error._id, {$set: {seen: true}});
});
};
errors.js:
Errors = {
// Local (client-only) collection
collection: new Meteor.Collection(null),
throw: function(message) {
Errors.collection.insert({message: message, seen: false})
},
clearSeen: function() {
Errors.collection.remove({seen: true});
}
};
But looks like Template.meteorError.rendered method doesn't work. And I can't set status of elements from my error's collection as seen: true.
When I call for example:
(server)
throw new Meteor.Error 401, "You need to login to add a new address"
(client)
Meteor.call "verify_address", address, name, (error, result) ->
if error
Errors.throw error.reason
I got this error message in my markup, but my browser console shows:
Errors.collection.find().fetch()
[Object]
_id: "MZ8TzpsKCXaeC33Jn"
message: "Address not the correct size"
seen: false
__proto__: Object
And message's seen attribute is still "false".
The initial problem was that an error has a 'X' icon that does not remove the error when clicked. How are we supposed to remove the errors?
The reason for the strange behavior is, you are manually throwing a Meteor.Error whereas your template is bound to a collection which is populated by calling Errors.throw(message)
Try this:
Errors.throw('You need to login to add a new address');

Categories

Resources