Store an uploaded image to Github using NodeJS and Github API - javascript

Been Struggling to try to push an Image to my repo on Github using NodeJS and Github API, I've covered the part of creating the SHA,Commit Tree and everything, the only thing left is to pass the image to the API and saving it as an actual Image (e.g test.png)
What I did so far is retrieving the image like below:
reader.onload = (e) => {
image = reader.result.split(',')[1]
}
Then sending it to the NodeJS server to get Sent to Github, but it's only stored as test.jpg but the content is not an actual Image but just :
/9j/4AAQSkZJRgABAQAASABIAAD/4QBARXhpZgAATU0AKgAAAAgAAYdpAAQAAAABAAAAGgAAAAAAAqA.....
Any help?

Based on this blog post, you might have to add ?raw=true to the end of the src url. Alternately, I found a hack on a previous SO answer.

Okay solved it! the only thing that I had to add is to actually convert the base64 content to Binary using this:
var data = Buffer.from(b64string, 'base64');
And then sending this data to a commit which worked perfectly!

Related

Image src changes when i update the image but frontend displays the old image

I have found weird bug in my application. I am using VueJS3 and typescript. I am creating a media gallery, where users can manage assets. All endpoints and backend side of application works perfectly. Currently i am working on updating image files(updating image field). My code works in theory, image url updates to a new one, but even the url is newer, image that is rendered is old image(before update). When i try to view my application in incognito window, my newer image is showing. But it does not work otherwise(works if and only user clears his cache) I hope i explained myself clearly, it is a little complicated :)
When i fetch the data from api, they don't have any src, so i have to create a property when using the data. Here is the code below.
const { res, err } = await this.$api.image.getAll(params)
res.data.items.forEach(async (image: Image<Populated>) => {
image.src = this.$fileHandler(image._id)
})
Note: File handler is a special method that gives the image source by id
Apparently your assets get cached, and there are multiple ways to solve that.
Not diving too much into caching strategies and cache control tags, just do
image.src = `${this.$fileHandler(image._id)}?_=${+new Date()}`
This will generate a unique (almost) URL for your image, invalidating every previous cached one.

JS convert base64 image to image file

Basically I have an img on a server and I access that using fetch which also authenticates the img. Ive seen online that I would need to convert it to base64 in order to display it. Im using React and ANTD and its for an image uploader. The uploading part is fine but the problem is when I log back into the page, I only have the file name saved so I need to make the call to the server which is in the fetch. Then I try to set the new vars to logoFileList. I need to see the image preview. What properties of the image object does the antd file uploader use?
fetch()
.then(res => {
const data = `${Buffer.from(res.url).toString(base64)}`;
const fileList = [...logoFileList];
fileList[index].url = data;
fileList[index].thumbUrl = data;
setLogoFileList(fileList);
})
Ive spent all day working on this any help would be great. Thanks.
I cant just display the image url because its authenticated and gives me a 403 error.

Storing a media(image,audio) on Amazon s3 and retrieving and showing it on browser

I am new to jsp and s3 . I am trying to solve a problem which is:
I need to save some media file say some kind of Images on s3 which I am doing by using s3client.putObject function of AmazonS3. From here I am getting the url of s3.
url is like https://abc.s3.amazonaws.com/18463/doc/xyz_1.jpg.
From some other part of project now I need to get the object and render it to browser. I am not able to solve this issue. How will I get the s3Object and render it in the form of Image.
I have tried to solve it by using StreamingOutput . I am getting the inputstream. but it is something which is weird. generally when the base64 format of image stream is appended with <img src="data:image/jpeg;base64,'+ escape(result)> it converts into the image format. but this is not happening in this scenario.
I am totally clueless how can I achieve the solution.
Any help will be highly appreciated.

Displaying images stored in MongoDb

I have an pinterest like application. Images and other related information are stored in MongoDb. Generally size of images is about 1 mb. Images are displaying with infinite scroll. When long script with base64 string is loaded, browser crashes or response time is really high (especially for Internet Explorer)
What is the best way to display images that are stored in MongoDb?
I think the best way to achieve this, is to have you file physically in some public folder on your server. This should be accesible in a way that you will only need to use something like
http://www.myhost.com/images/my/path/to/image.jpg
You can still maintain your Base64 image in mongodb as backup, however, this is not the best way to retrieve you images due performance issues (as you have seen). I recommend you to do the following:
Each time you store the image on mongo, be sure to also store the "image file" as itself on some public place on your server. Have in mind that you should keep the path to that file on the mongo model you are using. So, the next time you call the object, rather than get the base 64 image, you should only get the path to the image.
Lets say, you have this model
myModel = {
name: "some name",
image64: "someextralongstringveryveryveryweird......",
imageUrl: "/images/my/path/to/image/imagename-id.jpg"
}
the next time you query on it, you can just ignore the image64 using mongo projection, and in you client side you just use some html tag that makes use of that url.
<img src="/images/my/path/to/image/imagename-id.jpg">
This will help you lots on performance.
There are some libraries that could help you to manage the image file creation. ImageMagick is one that I have used and is so versatile.
I guess you have some server side part of this application? Why don't you create a tiny API to retrieve images?
So your browser will have information about image and can ask your server for it, something in line of http://your_server/api/image/imageID or http://your_server/images/imagename and then your server would just stream this image, you don't need to store this in the file system.
On the client side (browser) you just need to implement 'lazy loading'.
If you're using MongoDB, you should be storing images in your database using GridFS (http://excellencenodejsblog.com/gridfs-using-mongoose-nodejs/), a feature which exposes something like a virtual filesystem for your application.
Using GridFS, you could write a controller method which streams a requested file from your MongoDB instance and pipes the file content to the response.
I would recommend storing the images on the filesystem and using your web server to handle serving them to clients.
For performance, I would put them on a CDN - that will be able to handle the traffic.
In your application storage (mongo), you can store a URL/location to the image and then use that when retrieving the image in your javascript code.
In addition, in your code I would recommend preloading images via javascript that preloads images before the user has scrolled to see them. There are some great tools out there that you can leverage for that.
In the off chance that you cannot change the storage and you have to use mongo the way it is - I would look at preloading images with javascript.
I was having the same issue. So i used a mongodb to store my images.
This is how I proceeded:
Define a logo schema:
var logoSchema = new mongoose.Schema({
name: String,
url: String
});
Compile the logo schema into a model:
var Logo = mongoose.model("Logo", logoSchema)
Creating a new logo:
var rectblack = new Logo({
name:"rect&black",
url:"public/image.jpg"
});
Saving it :
rectblack.save(function(err, logo){
if(err){
console.log("some went wrong")
} else {
console.log("logo saved")
console.log("logo")
}
});
Now to use this logo or image I just called it with the image tag (just the file name!!!):
<img src="/image.jpg">.

upload image from local computer and saving them to a folder with redactor in meteorjs

I am using redactor plugin with meteorjs, to format the texts and add images, videos and links.Redactor supports uploading images as a web link, but here I wanted to add a button to upload images from local machine. For this I have added the button to the redactor. It is showing the browse image selection and is working.
$('.editor').redactor({
imageUpload:"/upload",
imageUploadCallback: function(image, json)
{
console.log(image);
console.log(json);
},
imageUploadErrorCallback: function(json)
{
console.log(json.error);
}
});
When I print console.log("#redactor_file").val()); it gives the name of the file. But, when I do console.log(console.log(html);) its gives <p><img src="undefined"></p>. Can I get the link or the url of the image here. If yes then how?
HTTP.methods({
'upload': function(data) {
console.log(data)
return JSON.stringify( {'data':"data"})
}
});
When I do console.log(data) using the above code it shows me Image in String format. Now I want to store the Image using GridFS. Or is there any better way to store Image in MongoDB. If yes then tell me or guide me to store image using GridFS ?
While Redactor provides a client-side method for uploading files, it does not provide a server-side method for receipt of uploaded files. Also, stock Meteor doesn't provide such a method either.
So you have a few choices. First is through using a router such as Iron Router, which you could create a server-side /uploads route, and Iron Router gives you access to the request, response objects. Which might work, but because this is no longer over DDP, you don't have access to Meteor.userId, etc. See How to respond server-side to routes using Meteor and Iron-Router?
A more Meteor-like way of doing the file upload is Meteor File or CollectionFS though I'm not sure how simply these would integrate with Redactor. You could definitely get them to work together, just off the top of my head I don't know how easy it would be.

Categories

Resources