Image not Uploading while using multer single image input option? - node.js

I am using multer to upload single image...
router.post('/register', upload.any(), function(req,res,next){
var img = req.files;
}
If I print the img the it is showing the object properly( originalname, mimeType, size etc) but when i trying to add the propertys in individual variable ( originalname = img.originanae;/req.files.originalename;) then originalname is showing undefined.
Why ??

use req.files[0].originalname instead of req.files.originalname

Related

How to upload video or image file to database

I am working in a project in which i need to create api using nodejs to upload video or image file to the postgres database
How i can do this
Thanks a lot
You can convert an image or video to base64, and then upload the base64 encoded string to your database.
const fs = require('fs');
function encode_base64(file) {
const bitmap = fs.readFileSync(file);
return new Buffer(bitmap).toString('base64');
}
const image = encode_base64('image.jpg');
const video = encode_base64('image.mp4');

How to know file type of some file uploaded in a form with nodeJS?

I would like to know the type of file obtained with req.files in NodeJS. I need this because the file uploaded has to be a photo for the well work of the app. It not only helps me to check that it is not a .jpg since you can make a .txt and change the extension.
The form is the following:
form(class="form add-form space-down" method="POST" enctype="multipart/form-data")
div.title
h1 UPLOAD NEW PROGRESS
div.form-group
label(for="weight") Weight:
input(type="number" name="weight" class="form-control" placeholder="Enter your weight")
div.form-group
label(for="front") Upload a front photo
input(type="file" name="front" accept="image/*")
div.form-group
label(for="from_side") Upload a from side photo
input(type="file" name="from_side" accept="image/*")
div.form-group
label(for="backwards") Upload a backwards photo
input(type="file" name="backwards" accept="image/*")
And the router handle is the following to obtain the photos uploaded:
routerProgress.post("/home/upload-progress", (req, res) => {
const front = req.files.front;
const from_side = req.files.from_side;
const backwards = req.files.backwards;
}
How can I be sure that front, from_side and backwards are photos?
If anyone has any idea how to do it, I would be very grateful if you could help me.
You can do something like this. Create a function which returns the extension of the file and you can check if it is a valid image extension or not.
routerProgress.post("/home/upload-progress", (req, res) => {
const front = getFileExtension(req.files.front);
const from_side = getFileExtension(req.files.from_side);
const backwards = getFileExtension(req.files.backwards);
if (front) {
// its an image, do something
}
}
function getFileExtension (filename) {
const allowedFileExt = ['JPEG', 'JPG', 'PNG', 'GIF', 'TIFF', 'PSD', 'PDF']; // you can add as per your requirement
const fileExt = /[^.]+$/.exec(filename);
return allowedFileExt.includes(fileExt[0].toUpperCase());
}
If that is the case, you should use mmmagic, it checks the content of the file instead checking only the extension. Try using this lib it will be more useful for your use case. Also, take a look at this npm package image-type

Node.js pipe image into memory and display it

I am making a Node.js/Electron application that downloads and displays images. I am downloading an image from the internet using request. I want to save this image in memory and display it without saving the file on the local hard drive. I am aware I could accomplish what I am asking here by inserting <img src="url"> into the DOM, but this is a heavily simplified version of my code and what I am trying to accomplish can not be done with that.
var image = fs.createWriteStream(?); // Is there anyway to save the image to memory?
request(url).pipe(image);
$('img').exampleScriptToSetImage(image); // And is there any way to display that image in a element without saving it to the local disk and loading its path?
Indeed! You can pipe your requested image data into a concat stream, convert the buffer to base64, and set the base64 encoding as your image source.
var path = require('path')
var request = require('request') // or hyperquest, simple-get, etc...
var concat = require('concat-stream')
var image = request(url)
image.pipe(concat({ encoding: 'buffer' }, function (buf) {
var ext = path.extname(file.name).slice(1) // assuming you have the file name
if (ext === 'svg') ext = 'svg+xml'
var src = 'data:image/' + ext + ';base64,' + buf.toString('base64')
var img = document.createElement('img')
img.src = src
document.body.appendChild(img)
})

Get file name in express request stream

Im wondering if is posible to know what is the file name of an incomming binary request.
This is my situation I have this code that handles the file upload
router.route('/:filename')
.put(function(req,res){
var uuid = guid();
var fileExtension = req.params.filename.substring(req.params.filename.lastIndexOf("."));
if(!fs.existsSync('../files')){
fs.mkdirSync('../files')
}
var newFile = fs.createWriteStream('../files/'+uuid+fileExtension);
req.pipe(newFile);
req.on('end',function(end){
console.log("Finished")
res.send(uuid+fileExtension)
})
})
as you can see now ,I need the file name specified in the URL('/:filename'). My question is: If it is possible to take that attribute from the resquest stream, instead the url or a form key?
If you use multer middleware you can access the uploaded filename like so
var multer = require('multer')
var upload = multer()
router.route('/:filename')
.put(upload.single('fileField'),function(req,res){
var fileName = req.file.originalname
var uuid = guid();
var fileExtension = req.params.filename.substring(req.params.filename.lastIndexOf("."));
if(!fs.existsSync('../files')){
fs.mkdirSync('../files')
}
var newFile = fs.createWriteStream('../files/'+uuid+fileExtension);
req.pipe(newFile);
req.on('end',function(end){
console.log("Finished")
res.send(uuid+fileExtension)
})
})
You'll need to inspect the Content-Disposition header of the request and parse the file name information out if processing the HTTP request manually.
However, I'd recommend you look at some of the existing file upload middlewares, no point in reinventing the wheel
busboy
multer
formidable
multiparty
pez

Convert multer file to string

I'm using multer to read in multi-part form data. However, I don't actually want to upload it. I want to put its contents into a string. Is there a simple way to do this?
Non-file fields are not stored on disk when you use multer's DiskStorage (the default storage type).
However, if you want files to be stored in memory too, then you need to use multer's MemoryStorage which will store files as Buffers, which you can then convert to string if you like:
var storage = multer.memoryStorage();
var upload = multer({ storage: storage });
// ...
app.post('/profile', upload.single('aboutme'), function(req, res) {
console.log(req.file.buffer);
});

Resources