How do I get the file name from nodejs app.post? - node.js

I want to get the file original name from this app.post (used with multer):
app.post('/', upload.array('file'), function(req, res){
console.log(req.files);
res.status(204).end();
});
Using console.log(req.files) I get:
[ { fieldname: 'file',
originalname: 'TSy16rd913.jpg',
encoding: '7bit',
mimetype: 'image/jpeg',
destination: './public/uploads/',
filename: 'TSy16rd913.jpg',
path: 'public/uploads/TSy16rd913.jpg',
size: 110736 } ]
Using console.log(req.files.originalname) or console.log(req.files.filename) gives undefined.
So how do I get originalname or filename?

As #Roland Starke answer, req.files is an array, so you have to do something like this
req.files[0].filename
To get all filenames :
req.files.forEach(function(value, key) {
console.log(value.filename)
})

Related

No folder is being created upon uploading of files

I am trying to upload pdf/xls/xlsx on the file server but whenever I try to send the file on my back end using FormData, no folder is being created and the file isn't uploaded either.
Here is my code on the front end (Vue):
let toSubmit = {
document_title: this.document_title.toUpperCase(),
added_by: this.userInfo.employeeCode,
FileName: `${this.document_title.replace(/ +/g, "_").toUpperCase()}.${this.$refs.files.files[0].name.split(".").pop().toLowerCase()}`
}
const formData = new FormData
formData.append("toSubmit", JSON.stringify(toSubmit))
_.forEach(this.uploadFiles, file=>{
formData.append("files", file)
})
const url = `${this.api}add/template/document`
axios.post(url, formData, {
headers: {
'Content-Type': 'multipart/form-data',
dataType: 'json',
}
}).then(res=>{
console.log('document template', res.data)
})
And on my back-end, I used multer for uploading the file but I have no idea if the problem lies on multer itself or if I have something missing in my code. Anyway, this is my code on the back end (Node):
API
router.post("/add/template/document", uploadTemplate.array("files"), (req, res)=>{
let myData = JSON.parse(req.body.toSubmit)
res.send(myData)
})
Uploading
const uploadTemplate = multer({storage: storageTemplate});
const storageTemplate = multer.diskStorage({
destination: (req, file, cb) => {
var dir = `./uploads/DocumentTemplates/`;
if (!fs.existsSync(dir)){
fs.mkdirSync(dir);
}
cb(null, dir);
},
filename: function(req, file, cb){
let myData = JSON.parse(req.body.toRequest);
let fileName = myData.FileName
let new_filename = `${fileName}`
cb(
null,
new_filename
)
}
})
I still can't figure out why no folder is being created. Am I missing something?
you're creating a subfolder without recursive flag, that's why the folder is not created
also, there is no body in multer middleware, only file, so you cannot send custom data to file like that, you need to change upload middleware
to create subfolders, add this flag:
fs.mkdirSync(dir, {recursive: true});
there is no body in multer, use file (you can add mimetype validation, check that only certain types are uploaded):
filename: function(req, file, cb){
console.log('file', file);
// validate expected file against file.mimetype
// if it fails, return error: cb(yourErrorMessage, null);
cb(
null,
file.originalname // handle on front-end
)
}
and on the frontend:
formData.append("files", file, 'filename goes here');

How to unit test with SuperTest to post files with multer

Right now, I have a form which submits an array of image 'files' using multer and aws-S3 and receives the following type of object for processing in the POST controller:
files: [
{
fieldname: 'uploaded',
originalname: 'test.jpg',
encoding: '7bit',
mimetype: 'image/jpeg',
size: 1407923,
bucket: 'mybucket',
key: '2343.jpg',
acl: 'public-read',
contentType: 'application/octet-stream',
contentDisposition: null,
storageClass: 'STANDARD',
serverSideEncryption: null,
metadata: null,
location: 'https://mybucket.s3.us-east-2.amazonaws.com/12144etest.jpg',
etag: '"7503d8c8f9cdca"',
versionId: undefined
}
]
How can I post an mock object like this with supertest? Right now I have this but I'm getting a 500 internal server error so clearly I'm doing something wrong:
let res = await api
.post("/login")
.send({"username" : "user", "password": "pass"})
await supertest(app)
.post('/upload')
.attach('files', 'test.jpg')
.set('cookie', res.headers['set-cookie'])
Using full path of file will fix your problem.
await supertest(app)
.post('/upload')
.attach('files', `${__dirname}/test.jpg`) // added __dirname here.

Image Uploading in NodeJS

I am trying to upload image on the server in NodeJS using multer and I was successful in my task but the thing is I want to send back the file object to the client.
Here is the some piece of the code
uploadRouter.route('/')
.post(authenticate.verifyUser, authenticate.verifyAdmin, upload.single('imageFile'), (req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'application/json');
console.log(req);
res.json(req.file);
})
When I send the request in postman to the server. It is showing 200 status. File is also uploaded on the server but in postman response it's showing blank.
Here is the screenshot of postman
When I logged the req.file object it's showing undefined
but when I logged req object here is what I got
IncomingMessage {
.....
file: {fieldname: 'imageFile', originalname: 'alberto.png', encoding: '7bit', mimetype: 'image/png', destination: 'public/images', …}
.....
}
if this file object is inside the req object then why I am not able to access by req.file?

Multer can't get sperate field name in console.log

I created an Express app in combination with multer to upload items in my Node.js app.
In my multi-upload setup I need to get the fieldname property for each item separately.
With console.log(req.files); I get all uploaded items as seen in the code below.
But how do I get fieldname? I'd like to do something like
console.log(req.files.upfile);
console.log(req.files.upfile2);
I hope someone here knows how to do this. Would highly appreciate help, thanks!
[ { fieldname: 'upfile',
originalname: 'test_file1.jpg',
encoding: '7bit',
mimetype: 'image/jpeg',
destination: 'storage/',
filename: 'test_file1.jpg',
path: 'storage/test_file1.jpg',
size: 1046949 },
{ fieldname: 'upfile2',
originalname: 'test_file2.jpg',
encoding: '7bit',
mimetype: 'image/jpeg',
destination: 'storage/',
filename: 'test_file2.jpg',
path: 'storage/test_file2.jpg',
size: 632169 } ]
As you are uploading multiple files and using array then you can iterate your request as below in router API Call
let files = req.files;
files.forEach((file) => {
console.log(file.fieldname);
});

gridfs-stream upload a file into mongodb not working in node.js server code

gridfs-stream upload a file not working, but download a file working plz give solution
app.post('/file', function(req, res) {
var busboy = new Busboy({
headers: req.headers
});
var fileId = new mongo.ObjectID();
var file = filename();
busboy.on('file', function(fieldname, file, filename, encoding, mimetype) {
if (!file) return res.send({
result: 'NO_FILE_UPLOADED This Error by not upload any file'
});
console.log('File [' + fieldname + '] got ' + data.length + ' bytes');
var writeStream = gfs.createWriteStream({
_id: fileId,
filename: my_file.txt,
mode: 'w',
chunkSize: 1024,
root: fs,
content_type: mimetype
});
// here how can i give a path to read stream ?
// File id is a mongodbid its ok. but what about file name
fs.createReadStream('/some/path').pipe(writestream);
}).on('finish', function() {
res.writeHead(200, {
'content-type': 'text/html'
});
res.end('download file');
});
req.pipe(busboy);//its working
});
gridfs-stream file upload code is not working file download code is working very well.how can i set the path of the readstream files in the path.
busboy never directly writes to disk. What you get is just a plain readable stream (file), so pipe that to your writeStream:
file.pipe(writeStream);
instead of:
fs.createReadStream('/some/path').pipe(writestream);
Also your if (!file) check will never execute, because file will always be defined, and console.log('File [' + fieldname + '] got ' + data.length + ' bytes'); is wrong because there is no data variable in that scope.

Resources