I am using Twitter module for nodejs to upload media to my twitter account. As example program from here https://github.com/desmondmorris/node-twitter/tree/master/examples#media.
Instead of using image from system i am passing a base64 encoded string of the image. When i run this program it output the base64 string(image) in the console in a loop and after a while it crashes and doesn't upload my image.
// Load your image
var data = require('fs').readFileSync(image);
// Make post request on media endpoint. Pass file data as media parameter
client.post('media/upload', {media: image}, function(error, media, response){
if (!error) {
// If successful, a media object will be returned.
console.log(media);
// Lets tweet it
var status = {
status: 'I am a tweet',
media_ids: media.media_id_string // Pass the media id string
}
client.post('statuses/update', status, function(error, tweet, response){
if (!error) {
console.log(tweet);
}
});
}
else{
console.log("error upload");
}
});
So i tried different method. I saved the base64 encode image in to out.png
fs.writeFile("out.png", data.image, 'base64', function (err) {
console.log(err);
});
var data = require('fs').readFileSync("out.png");
and this code output error saying
Error: ENOENT: no such file or directory, open 'D:\Local server\nodejs\out.png'
This file does exist i have confirmed
Update
Api returns [Error: Status Code: 400]
hi there are several nodejs api which allows to serve as a client library for Twitter, and with which you can upload your media to your twitter account, the most popular twitter and are node-twitter-api
Related
I'm calling the Facebook API from a Node.js server in order to upload a video. The video has a thumbnail hosted on another server. I want to read the file from the server, pass it as a FormData to /{page-id}/videos.
I'm able to get the file and convert it to base64 data, however, everytime that I call the API I get the following error:
(#100) Invalid image format. It should be an image file data.
Here's my code:
try {
const data = await httpUtilBase.get(thumbnailUrl, { responseType: 'arraybuffer' });
thumbnailData = `data:${data.headers['content-type']};base64,${Buffer.from(data.data).toString('base64')}`;
} catch {
return next(new ErrorResponse('Cannot fetch thumbnail url', httpStatus.BAD_REQUEST));
}
const formData = new FormData();
formData.append('url', url);
formData.append('title', title);
formData.append('published', 'false');
formData.append('thumb', thumbnailData);
formData.append('access_token', facebookUtil.decryptToken(page));
I make the call to /{page-id}/videos just after and it always fails. I don't understand what the format should be.
I've been stuck on this problem for awhile now and can't seem to figure out why this file isn't being uploaded to firebase correctly. I'm using the code below in firebase functions to generate a document, then I convert that document to a stream, finally I create a write stream declaring the path that I want the file to be written to and pipe my document stream to the firebase storage WriteStream.
Example 1: PDF uploaded from file system through firebase console. (Link works and displays pdf)
Example 2: PDF generated in firebase functions and written to storage using code below
Considerations:
I know the PDF is valid because I can return it from the function and see it in my web browser and everything is as I would expect.
When trying to open the bad file it doesn't display anything and redirects me back to the overview screen.
const pdfGen = require("html-pdf");
pdfGen.create(html, { format: "Letter" }).toStream(function (err, stream) {
if (err) return res.status(500).send(err);
var file = storage.bucket()
.file(job.jobNum + "/quote-doc.pdf")
.createWriteStream({
resumable : false,
validation : false,
contentType: "auto",
metadata : {
'Cache-Control': 'public, max-age=31536000'}
});
stream.pipe(file)
.on('error', function(err) {
return res.status(500).send(err);
})
.on('finish', function(data) {
stream.close();
file.end();
res.end();
console.log('finished upload');
});
});
I am trying to send a picture from my mobile hybrid app (Ionic 3) to my Heroku backend (Node.js) and have the backend upload the picture to Firebase Storage and return the newly uploaded fil download url to the mobile app.
Keep in mind that I am using the Firebase Admin SDK for Node.js.
So I send the base64 encoded image to Heroku (I check the encoded string with an online base64 decoder and it is alright) which is handle by the following function:
const uploadPicture = function(base64, postId, uid) {
return new Promise((resolve, reject) => {
if (!base64 || !postId) {
reject("news.provider#uploadPicture - Could not upload picture because at least one param is missing.");
}
let bufferStream = new stream.PassThrough();
bufferStream.end(new Buffer.from(base64, 'base64'));
// Retrieve default storage bucket
let bucket = firebase.storage().bucket();
// Create a reference to the new image file
let file = bucket.file(`/news/${uid}_${postId}.jpg`);
bufferStream.pipe(file.createWriteStream({
metadata: {
contentType: 'image/jpeg'
}
}))
.on('error', error => {
reject(`news.provider#uploadPicture - Error while uploading picture ${JSON.stringify(error)}`);
})
.on('finish', (file) => {
// The file upload is complete.
console.log("news.provider#uploadPicture - Image successfully uploaded: ", JSON.stringify(file));
});
})
};
I have 2 major issues:
Upload succeeds but I when I go to Firebase Storage console, there is an error when I try to display the preview of the picture and I cannot open it from my computer when I download it. I guess it is an encoding thing....?
How can I retrieve the newly uploaded file download url ? I was expecting an object to be returned in the .on('finish), like in the upload() function, but none is returned (file is undefined). How could I retrieve this url to send it back in the server response?
I want to avoid using the upload() function because I don't want to host files on the backend as it is not a dedicated server.
My problem was that I add data:image/jpeg;base64,at the beginning of the base64 object string ; I just had to remove it.
For the download url, I did the following:
const config = {
action: 'read',
expires: '03-01-2500'
};
let downloadUrl = file.getSignedUrl(config, (error, url) => {
if (error) {
reject(error);
}
console.log('download url ', url);
resolve(url);
});
Just want simple file upload functionality . I have used fs-path that serves my purpose of creating dynamic folder structure and file at upload location. I am not able to achieve streaming of request file, that will have to be uploaded. My code is as follows :
fsPath.writeFile(path, **req.body**, function (err) {
if (err) {
throw err;
} else {
console.log('File Upload successful...');
res.send({ code: 200, message: `File Upload successful` });
}
});
Need some insights about, how can I send request file as input in the above code snippet. How do I steam my request file, that will be written in respective upload location?
If you want to stream the request body then instead of using a body parser or multr you should use the req stream directly. Remember that the request object is a stream and you can use it as such:
req.on('data', data => {
console.log(data);
});
You can also pipe it to some other stream, like a writable stream created with fs.createWriteStream etc.
I am writing a simple wrapper in node.js which calls Goole Places API and gets a photo using photo_reference. When I run this and process the request from Postman it works but does not display photo itself. In the code below mapsClient.placesPhoto does return a huge response with many tags. Its not just raw image data. My question is how do I extract image or image data from googleResp object and send it back to client?
var googleMapsClient = require('#google/maps').createClient({
key: 'xyz'
});
app.post('/getGooglePlacePhoto/:photoref', function(req, res){
googleMapsClient.placesPhoto({
photoreference: req.params["photoref"],
maxwidth: 70,
maxheight: 70
}, function(err, googleResp){
if (!err) {
debug('got response from google');
res.set('Content-Type','image/jpeg');
debug(googleResp.body);
res.send(200, googleResp.body);
} else {
debug(err);
res.send(409, err);
return;
}
});
});