I would like to be able to decode an base64 image and save it too a file I got it working with small base64 images but if the image is larger I guess the url cant decode the whole string for example.
app.get("/api/id/:w", function(req, res) {
var data = req.params.w;
var img = Buffer.from(data, 'base64');
const fs = require("fs");
fs.writeFileSync("new-path.jpg", img);
res.status(200).end(img);
});
i didnt try anything
Related
I am trying to read an image and text files and upload to aws s3 bucket using nodejs fs module. I am not using any express server, but plain javascript that calls aws-sdk and uploads items to aws-s3.
Here is how my project structure looks like
Inside s3.js I am trying to read the 2.png and friends.json files,
s3.js
const fs = require('fs');
const file = fs.readFileSync('../public/2.png', (err)=>console.log(err.message));
But this throw and error
Error: ENOENT: no such file or directory, open '../public/2.png'
What could be going wrong?
Could always try an absolute path instead of a relative and add encoding:
const fs = require('fs')
const path = require('path')
const image = path.join(__dirname, '../public/2.png')
const file = fs.readFileSync(image, {encoding:'utf8'})
Could also use upng-js with a Promise
const png = require("upng-js")
const fs = require('fs')
async function pngCode(img) {
try {
return png.decode(await fs.promise.promisify(fs.readFile)(img)
} catch (err) {
console.error(err)
}
}
pngCode('.../public/2.png')
None of the code is tested wrote on my phone.
That I would like to convert into a byte array.
I get the file with <v-file-input> and this is the input of it.
I would like to convert it on the client side, then send it to the backend to be uploaded to the sql server.
I've tried to search it on google for hours.
Try to add this file object to FormData and send it to nodejs. On a server side you can use multer to decode multipart formdata to req.file for instance
on a client side:
const formData = new FormData()
formData.append('file', file)
const { data: result } = await axios.post(`/api/upload-image`, formData)
on a server side:
const multer = require('multer')
const upload = multer()
...
router.post('/upload-image', upload.single('file'), uploadImageFile)
...
uploadImageFile(req, res) {
// multer writes decoded file content to req.file
const byteContent = req.file
res.end()
}
I've been trying to get a quick node.js api working, but I'm running into some issues and I was hoping someone could help.
What I'm trying to do: I'm trying to pass a base64 encoded image data URI to my node.js and have it save the file to my server. I believe that I've almost got it working, but for some reason the image is getting corrupted. When I attempt to run the script when I just hardcode the dataURI in, the saved image is perfect. However, when I use the GET request, the saved file is corrupted and I cannot open it.
Here is what I have so far:
const express = require('express');
const fs = require('fs');
const app = express();
app.listen(3000, () => { console.log
('Running on port 3000...');
});
app.get('/api/users', function(req, res) {
let base64String = req.param('datauri');
let base64Image = base64String.split(';base64,').pop();
fs.writeFile('image.png', base64Image, {encoding: 'base64'}, function(err) {
console.log('File created');
});
res.send(base64Image);
});
Any help would be greatly appreciated!
You need to url decode the base64 string to replace the special characters back to their original form. I.E. swap + back to a space
You should be able to use decodeURIComponent()
var base_64 = decodeURIComponent(base_64_string);
I want to make user able to download a youtube video using node-ytdl.
For example when client side make a GET request for certain route the video should be downloaded in response.
var ytdl = require('ytdl-core');
var express= require('express');
//Init App Instance
var app=express();
app.get('/video',function(req,res){
var ytstream=ytdl("https://www.youtube.com/watch?v=hgvuvdyzYFc");
ytstream.on('data',function(data){
res.write(data);
})
ytstream.on('end',function(data){
res.send();
})
})
Above is my nodejs code. Even though in network it seems to download the response it does not make user download as a file.I don't want to store any file on server.It would be great if someone could help me how to solve the issue.
res object is a writable stream so you can directly pipe the output of ytdl to res object like this -
ytdl("http://www.youtube.com/watch?v=xzjxhskd")
.on("response", response => {
// If you want to set size of file in header
res.setHeader("content-length", response.headers["content-length"]);
})
.pipe(res);
You have to also pass the headers. Try it:
app.get('/video', (req, res) => {
var url = "https://www.youtube.com/watch?v=hgvuvdyzYFc";
res.header("Content-Disposition", 'attachment; filename="Video.mp4');
ytdl(url, {format: 'mp4'}).pipe(res);
});
If someone is still getting an error just update the package to latest version by running:
npm i ytdl-core#latest
Ok, so make a string var, then add data to it on the data event. On end, send everything. Here is an example:
const ytdl = require("ytdl-core"),
app = require("express")();
app.get("/video", (req, res) => {
let data = "", vid = ytdl("https://www.youtube.com/watch?v=hgvuvdyzYFc");
vid.on("data", d => data += d);
vid.on("end", () => res.send(data));
res.header("Content-Disposition", 'attachment; filename="Video.mp4');
});
I am trying to attach files to sendgrid without storing them to the disk. I want to use stream to handle that.
var multer = require('multer');
var upload = multer({ storage: multer.memoryStorage({})});
mail = new helper.Mail(from_email, subject, to_email, content);
console.log(req.body.File);
attachment = new helper.Attachment(req.body.File);
mail.addAttachment(attachment)
I think is not possible using streams because:
multer library with MemoryStorage stores the entire file contents on memory in a Buffer object (not a Stream)
Sendgrid library doesn't support Readable streams as input.
But you can achieve it using the returned buffer as attachment like:
var multer = require('multer')
, upload = multer({ storage: multer.memoryStorage({})})
, helper = require('sendgrid').mail;
app.post('/send', upload.single('attachment'), function (req, res, next) {
// req.file is the `attachment` file
// req.body will hold the text fields, if there were any
var mail = new helper.Mail(from_email, subject, to_email, content)
, attachment = new helper.Attachment()
, fileInfo = req.file;
attachment.setFilename(fileInfo.originalname);
attachment.setType(fileInfo.mimetype);
attachment.setContent(fileInfo.buffer.toString('base64'));
attachment.setDisposition('attachment');
mail.addAttachment(attachment);
/* ... */
});
It may affects memory usage (out of memory errors) if used with big attachments or high concurrency.