Firebase Storage | Angular 2 - Proper way to display image after upload - javascript

When creating an event, I also upload an image to Firebase Storage.
Then I create an array this.eventz to display the events on the home page. For each event I want to retrieve the image as well, but I get a Firebse error:
FirebaseStorageError {code_: "storage/object-not-found", message_: "Firebase Storage: Object 'events/-KxCuUuss1I2uFolk99m/-KxCuUuss1I2uFolk99m_main.png' does not exist.", serverResponse_: "{↵ "error": {↵ "code": 404,↵ "message": "Not Found. Could not get object"↵ }↵}", name_: "FirebaseError"}
I understand that the image isn't uploaded yet when I want to include it in the array but I don't know how to fix my problem. The code works fine. It displays all the events, adds images to each one ... it's just that error when creating a new event.
getEventImage(event) {
if (event) {
const mainPhotoRef = firebase.storage().ref('events');
console.log(mainPhotoRef);
mainPhotoRef.child(`/${event.key}/${event.key}_main.png`).getDownloadURL()
.then(url => this.makeEvents(url, event))
}
}
makeEvents(url, event) {
console.log(url);
if (url) {
try {
event.img = url;
let index = _.findIndex(this.eventz, ['key', event.key]);
if (index >= 0) {
this.eventz.splice(index, 1);
}
this.eventz.push(event);
} catch (err) {
console.log(err);
}
}
}

I fixed my problem by saving the url to the event object when creating it. I would like to know if I am uploading correctly.
private uploadPhoto(itemKey): void {
this.myPhotosRef.child(itemKey).child(`${itemKey}_main.png`)
.putString(this.myPhoto, 'base64', { contentType: 'image/png' })
.then((savedPicture) => this.updateEventImage(savedPicture.downloadURL, itemKey));
}
updateEventImage(url, itemKey) {
console.log(url);
const newEvent = this.db.object(`events/${itemKey}`)
newEvent.update({ eventImage: url });
}

Related

Is there faster way about javascript autocomplete?

Goal : faster way autocomplete
Situation: I use vue js, when open the page, execute in mounted()
axios.get('http://127.0.0.1:3000/games/all')
.then(res=>{
this.$store.state.games = res.data;
this.$store.dispatch('GetGames',res.data);
})
.catch(err=>console.log(err))
axios get games/all is
router.get('/all',(req,res,next)=>{
let responseData = {};
Game.find({},(err,rows)=>{
if(err) throw err;
if(rows.length) {
responseData.result = 1;
responseData.data = rows;
}else{
responseData.result = 0;
}
res.json(responseData.data);
// console.log(responseData.data);
});
})
I got a json file like
{
{ gamename:"agricola",
maxplayer:4,
minplayer:1,
mintime:20,
maxtime:90,
difficulty:"hard",
}
}
There are 200~300 columns.
Using vuex
state: {
games:"",
},
mutations: {
getGames(state,payload){
state.games = payload;
console.log("받아온 게임",state.games);
},
}
GetGames:({commit},payload)=>{
commit('getGames',payload)
},
When I bring db, using state in store.js file, so I use autocomplete
const autocomplete = document.querySelector(".autocomplete");
if (this.gameInput) {
this.result = this.games.filter((game) => {
return game.gamename.match(new RegExp(this.gameInput, "i"))
});
} else {
autocomplete.classList.add("disabled");
}
the gameInput is your typing
Problem: it takes too long to bring the DB (4000ms~) and Data is stored in local storage. Even after receiving the data, I cannot search unless refresh it. so user has to stay until bring the db, and user cannot search game until refresh the page. I want they don't need to refresh my page. thanks for read my question. sorry about my poor English (tear)

React | Facebook JS API : Error code 100 when trying to upload multiple images to my page feed

In a first function, I upload multiple images to page-id/photos and receive a positive response with all the ids of these images.
The next part however is where I'm stuck; I am now trying to create a post with multiple images to my Facebook page timeline. However, I'm getting a weird error response claiming that I already have uploaded my images.
I've even followed Facebook's own example from their documentation using Open Graph Explorer, but that just returns another error
Function to send image:
(works without a problem)
sendFacebookImagePost(page) {
const attached_media = []
for(let i = 0; i < this.state.upload_imgsrc.length; i++) {
let reader = new FileReader();
reader.onload = (e) => {
let arrayBuffer = e.target.result;
let blob = new Blob([arrayBuffer], { type: this.state.upload_imgsrc[i].type });
let data = new FormData()
data.append("source", blob)
data.append("message", this.state.fb_message)
data.append("no_story", true)
data.append("published", true)
axios({
method: "post",
url: "https://graph.facebook.com/" + page.id + "/photos?access_token=" + page.accessToken,
data: data
})
.then(response => {
attached_media.push({media_fbid: response.data.id})
if (attached_media.length === this.state.upload_imgsrc.length) {
this.sendFacebookPost(page, attached_media)
}
})
.catch(error => {
console.log(error);
})
}
reader.readAsArrayBuffer(this.state.upload_imgsrc[i]);
}
}
Function to send post:
(Here is where the error happens)
sendFacebookPost(page, attached_media) {
let data = {
message: this.state.fb_message,
link: this.state.fb_link,
attached_media: attached_media
// this is what attached_media returns:
// [
// {media_fbid: response.data.id},
// {media_fbid: response.data.id}
// ]
}
axios({
method: "post",
url: "https://graph.facebook.com/" + page.id + "/feed?access_token=" + page.accessToken,
data: data
})
.then( () => this.setState({fb_successMessage: "Post successful!", fb_errorMessage: ""}) )
.catch(error => {
console.log(error);
})
}
Error code
error: {
code: 100
error_subcode: 1366051
error_user_msg: "These photos were already posted."
error_user_title: "Already Posted"
fbtrace_id: "Cl9TUTntOZK"
is_transient: false
message: "Invalid parameter"
type: "OAuthException"
}
My try on Open Graph Explorer
Problem solved.
The part that went wrong is where I add the following to my image post:
data.append("published", true). Apparently, images you want to use in a multi photo post have to be set to published: false before they can be used in a post. Otherwise, Facebook sees this as already uploaded.

Meteor Files Storing a image url in Mongo collection

I'm really lost when it comes to file uploading in meteor and manage the data between client and server.
I'm using Meteor Files from Veliov Group to upload multiple images on the client side. They're getting stored in a FilesCollection called Images and I have my Mongo.Collection called Adverts.
collections.js:
Adverts = new Mongo.Collection('adverts');
Images = new FilesCollection({
collectionName: 'Images',
storagePath: () => {
return `~/public/uploads/`;
},
allowClientCode: true, // Required to let you remove uploaded file
onBeforeUpload(file) {
// Allow upload files under 10MB, and only in png/jpg/jpeg formats
if (file.size <= 10485760 && /png|jpg|jpeg/i.test(file.ext)) {
return true;
} else {
return 'Limit 10mb';
}
}
});
// if client subscribe images
if (Meteor.isClient) {
Meteor.subscribe('files.images.all');
};
// if server publish images
if (Meteor.isServer) {
Images.allowClient();
Meteor.publish('files.images.all', () => {
return Images.collection.find();
});
};
What I'm trying to achieve is, when I upload the images, I wanna store the URLs on the document in Adverts that I'm working with (I'm using iron:router to access those documents _id).
I managed to get the URL but only for the first image uploaded, my code for what I saw on the docs:
Template.imageUpload.helpers({
imageFile: function () {
return Images.collection.findOne();
},
myImage: () => {
console.log(Images.findOne({}).link())
}
})
Template.imageUpload.events({
'change #fileInput': function (e, template) {
if (e.currentTarget.files) {
_.each(e.currentTarget.files, function (file) {
Images.insert({
file: file
});
});
}
}
})
I was using a Meteor.Call to send the URL to the server, but I couldn't manage to update the document with a new property pic and the value url of the image
server.js:
imageUpload: (actDoc, imgURL) => { // actDoc is the document id that I'm working on the client
Adverts.update({'reference': actDoc}, {$set: {'pic': imgURL}})
},
This is probably a dumb question and everything might in the docs, but I've readed those docs back and forth and I can't manage to understand what I need to do.
The answer for my problem was to do it server side
main.js server
FSCollection.on('afterUpload'), function (fileRef) {
var url = 'http://localhost:3000/cdn/storage/images/' + fileRef._id + '/original/' + fileRef._id + fileRef.extensionWithDot;
}
MongoCollection.update({'_id': docId}, { $set: {url: imgUrl }}})

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

Uploading Avatar on Parse (using AngularParse Service)

{"name":"tfss-4dde4ec8-e678-495a-a5d0-d3e51f0bdafc-search-pic-img6.jpg","url":"http://files.parsetfss.com/d130ccda-cf9f-4264-999e-09305bed0fd1/tfss-4dde4ec8-e678-495a-a5d0-d3e51f0bdafc-search-pic-img6.jpg"}
This is the return Object, When I upload the file on the parse server. I want to use this object to store it on the Parse Class avatar column as type "file" not string. In short I am trying to store it as image file after uploading. I want to do it in Cloud Code javascript rather than on html javacript. I want to send the object to parse and store it as image file.
Here's my cloud code. I am new to parse a bit.
Parse.Cloud.beforeSave("editProfileweb", function(request) {
var avatar = request.object;
var user = request.user;
if (user) {
user.set("avatar",avatar);
user.save(null, {
success: function(user) {
response.success();
},
error: function(error) {
// Show the error message somewhere and let the user try again.
response.success();
}
});
} else {
response.error("User not authenticated");
} });
I guess this is what you are looking for
Object.set({columnName: {"name": File.name, "url": File.url, "__type": "File"}});

Categories

Resources