Directory folder to store document - node.js

I am trying to make document management project using nodejs,mongodb and react. I want to make directory folder that will store document and the sub is it file. But I could not find any reference that I could use to start making the directory. Is there any specific term that I should search to get any reference to start the project? Thank you.

You can use Multer library for file uploads. It's super easy to use.
import multer from 'multer';
//specify where you want your files to be stored
var fileStorageEngine = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, './images')
},
filename: function (req, file, cb) {
cb(null, Date.now() + '--' + file.originalname)
}
})
var upload = multer({ storage: fileStorageEngine });
//pass it as a middleware to a route where you expect to get a file upload
app.use('/api/file/', upload.single('image'), someRouterHere);

Related

Node.js does multer with diskStorage create a folder if it doesn't exist?

I have a small app that receives via POST a file and stores it in a specific folder.
I know that this line:
const multer = multer({ dest: ‘media' })
(of course with some more code, where I use the multer.single('somefilename')) will create a new folder named media if it doesn't exist already.
But I want to be able to control the name given to the file and some other stuff, so I'm using it with diskStorage instead:
const x = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'media')
},
filename: function (req, file, cb) {
cb(null, file.originalname);
}
})
const multer = multer({ storage: x })
(there's some more code of course with multer.single('somefilename'))
It works fine when the folder 'media' already exists, but doesn't create it if it doesn't - is it supposed to, or only the simpler multer can do that?
Thanks in advance!
It won't create the folder, they warn that in the official doc:
Note: You are responsible for creating the directory when providing
destination as a function. When passing a string, multer will make
sure that the directory is created for you.
Below is an example of how to create the entire path, but exist many alternatives:
const path = require("path");
const shell = require('shelljs');
const fullPath = path.join(__dirname, '..', '..', "uploads");
shell.mkdir('-p', fullPath);
As #robertklep suggest, please consider: fs.mkdir() instead of shell:
fs.mkdir(path.join(__dirname, 'test'), { recursive: true })

Store images with Multer and store only the path in MongoDB

So part of my Schema looks like this photo: [{data: Buffer, contentType: String }]
And Multer stores the images like so:
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, './public/uploads');
},
filename: function (req, file, cb) {
cb(null, file.fieldname + '-' + Date.now());
}
});
app.use(multer({
storage: storage
}).single('photo'));
Now I know it stores the images as a Buffer in Mongodb and stores the files on the server too. I would like it stored the path to the file in the database and then have it store the actual image file on the server. It stores the images as text files it seems, encoded with utf-8. This is an awfully complicated process for a seemingly simple task (store images)
You can access the path of the file using the req.file.path
app.post("/file", function(req, res) {
console.log(req.file.path)
})

Node: multer change destination folder for fields

I have simple multer image uploading.
// Multer settings
// STORAGE FOR USER AVATAR
var storageAvatar = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'public/uploads/avatars/')
},
filename: function (req, file, cb) {
cb(null, req.user.id + '.jpg')
}
})
// STORAGE FOR ARTICLE THUMBNAILS
var storageThumbnail = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'public/uploads/thumbnails/')
},
filename: function (req, file, cb) {
cb(null, "clanok" + '.jpg')
}
})
// SETTING UPLOAD FOLDER
var upload = multer({
storage: storageAvatar
})
// Multer BEFORE CSRF!!!
app.use(upload.fields([{
name: 'avatar',
maxCount: 1,
}, {
name: 'thumbnail',
maxCount: 1,
}]));
my problem is that i am unable to set different folder for avatars and thumbnails. I can set only one folder for both :/ Anything else i tried ends with invalid CSRF. Thanks for anny suggestions.
EDIT: in one form i am using only one thing. So for example in profile update i have only possibility to change avatar in article adding i have only ability to change thumbnail of article. They not need to bey in upload fields can be seperate but dont know how.
I found on forum way how to go over csrf problem by adding ?_csrf={{csrfToken}} to the end of action in form so i can use official way of using multer :)

How to view an image in new tab instead of download in NodeJS using Multer

I'm using Multer and express to add image via a form. I have successfully created the file in an uploads folder. When I try to call the url it is being downloaded in a file format. I need to open it in a new tab based on mime type.
What is the best way to achieve this?
Below is my code:
app.use('/images', express.static(__dirname + '/file/uploads/'));
Sample url:
http://localhost:2020/images/b78339184694e2e6864a77d4f3067db5
I added filename in my storage variable to achieve the required result.
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, __dirname+'/file/uploads/')
},
filename: function (req, file, cb) {
console.log(file);
var extArray = file.mimetype.split("/");
var extension = extArray[extArray.length - 1];
var name = crypto.randomBytes(10).toString('hex');
cb(null, name + Date.now()+ '.' +extension)
}
});

Using Multer and Express to upload and display files

I'm using multer to upload images with express and node from a form, however all the files names come out like "8f92a1388f70c6c88eb32489f6bcfcc9". There isn't even an extension attached. How to I display this on the client side?
try:
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, '/where/ever/the/upload/dir/is')
},
filename: function (req, file, cb) {
cb(null, file.orignalname)
}
})
var upload = multer({ storage: storage })
Instead of:
var upload = multer({ dest: 'uploads/' })
Requesting the file:
With the proper permissions set on the file/or directory your server should be able to request it fine, remember to explicitly write the file name with an extension if you aren't doing anything fancy after the file is written ;)
If you want more control over your uploads, you'll want to use the
storage option instead of dest. Multer ships with storage engines
DiskStorage and MemoryStorage; More engines are available from third
parties.
--The Horse
(ref: github: expressjs/multer)
Note: Multer will not append any file extension for you, your function should return a filename complete with an file extension

Resources