Upload with dynamic Filename - multer/s3 - javascript

I use multer/multer-s3 to upload a Profilepicture to Amazon S3.
The Upload works well when i use a static filename like 'userPhoto_' which matches the the fieldname in the form.
var upload = multer({
storage: multerS3({
s3: s3,
bucket: '<bucketname>',
key: function (req, file, cb) {
cb(null, file.fieldname);
}
})
});
router.post('/api/photo', upload.single('userPhoto_123'), function (req,res) {
res.end("Uploaded!");
});
In my .ejs File i have the Input Field like
<input class="ui input" type="file" name="userPhoto_<%=person.id%>" />
So the question is how to pass the FieldName including the person.id to the upload.single - Middleware.
Thanks!

modify bucket value as -
req: is normal express request
bucket: (req, file, cb) => {
cb(null, ${req.dynamic_name});
};

Related

Node JS Multer Multiple Files Req.File Undefined

FIXED: ( NO req.file ) ( YES req.files )
My project need multiple files upload,
If i single image upload working, multiple image upload working ( upload to files ) and i need req.file.filename because i write mysql this image road.
Req.File = Undefined..
// Sinle image upload and write mysql..
Router.post('/uax_items_addOne', Upload.single('fileUrl'), Controller.Cnt_AddOne);
// Multiple image upload and undefined req.file
Router.post('/uax_items_multipleFile', Upload.array('fileUrl', 12), Controller.Cnt_MultipleFile);
// This is controller
exports.Cnt_MultipleFile = (req, res, next) => {
console.log(req.file); // This is write "undefined"
}
// This is my Storage
const Storage = Multer.diskStorage({
destination: function(req, file, callback) {
callback(null, './uax_Uploads/images');
},
filename: function(req, file, callback) {
callback(null, 'img-' + Date.now() + Path.extname(file.originalname));
}
});
var Upload = Multer({
storage: Storage
});
Multiple files are provided to you in req.files (note the s at the end).
If you want to simplify your POST queries, I would recommend using Multer's .fields() function, that let you group incoming file params (post-processing is done, both, with the files field).
For example:
upload.fields([
{ name: 'one_tag_param' , maxCount: 1 },
{ name: 'multiple_tag_param' , maxCount: 12 }
])

How to download files using multer-sftp

I have this code, but surfing the web, i cannot found some way to download a file from the remote server. I'm able to upload the files in the remote server but I don't have any idea how download from there.
var storage = sftpStorage({
sftp: {
host: '171.16.....',
port: xxxx,
username: 'username',
password: 'xxxxxxxxxxxxxxxx'
},
destination: function(req, file, cb) {
cb(null, 'uploads')
},
filename: function(req, file, cb) {
cb(null, Date.now() + file.originalname)
}
});
var upload = multer({ storage: storage })
This is the route to upload the files: (Works great!)
router.post('/upload-image', upload.single('file'), listarController.uploadImage);
This is the route to download the files - locally: (Searching a method...)
router.get('/get-file/:file', listarController.getFile);
The method to download locally:
controller.getFile = (req, res) => {
var file = req.params.file;
var path_file = './uploads/' + file;
fs.exists(path_file, (exists) => {
if (exists) {
return res.sendFile(path.resolve(path_file))
} else {
return res.status(200).send({
message: "The image doesn't exist."
})
}
})
}
Some suggestion? Thanks in advance
I solved it with the following libraries:
1. multer-sftp: To upload the files.
2. ftp: To download and rename the files.

can't change name to uploaded file using multer

I am trying to change the name of the image im uploading to the server using multer which gives the file a random name.
I user multer.diskStorage method to do so as described in the documentation but it keeps saving the file with random names
CODE:
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null,'./uploads/')
},
fileName: (req,file,cb) => {
cb(null, file.originalname)
}
})
const upload = multer({storage: storage})
router.post('/', upload.single('carImage') ,(req, res) => {
res.send(req.file);
}
RESPONSE :
{
fieldname: 'carImage',
originalname: 'testOCR8.jpg',
encoding: '7bit',
mimetype: 'image/jpeg',
destination: './uploads/',
filename: '229f70c20e5550dbe638db49791ef17d',
path: 'uploads/229f70c20e5550dbe638db49791ef17d',
size: 1712380
}
im uploading to the server using multer which gives the file a random name
You made a typo. It is filename not fileName. This is the standard behavior as per the docs.
filename is used to determine what the file should be named inside the folder. If no filename is given, each file will be given a random name that doesn't include any file extension.
So, your code should be
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null,'./uploads/')
},
filename: (req,file,cb) => { // notice the change 'filename'
cb(null, file.originalname)
}
});
const upload = multer({storage: storage});
Try a different approach for using StorageMulter. Try the following -
var StorageMulter = multer.diskStorage({
destination: function(req, file, callback) {
callback(null, "./temp");
},
filename: function(req, file, callback) {
var uploadFileName = "x.jpg"; //Manipulate this variable accordingly
callback(null, uploadFileName);
}
});
var upload = multer({
storage: StorageMulter
});
app.post("/api/uploaddocument", function(req, res) {
upload(req, res, function(err) {
if (err) {
return res.end("Something went wrong!"+ err);
}
});
});

Rename file using multer-ftp

I am trying to upload a file to an ftp using multer-ftp. It successfully uploads to the ftp however I need to change the name of the file. Is there a way to do this?
var upload = multer({
storage: new FTPStorage({
basepath: '/path',
ftp: {
host: host,
secure: false,
user: user,
password: pwd
}
})
}).single('fileupload');
app.post('/getfiles', function (req, res, next) {
upload(req,res, function(err){
if(err){
res.send('Error uploading file - ' + err);
}else{
res.send('File is uploaded - ' + JSON.stringify(req.file));
}
})
})
In req.file it has the original file name as it was uploaded. How can I get multer-ftp to upload the file using that name instead of the name it is coming out as (example format it is coming out as is 5acfbabc8430fb3d311ae365f448.png
Check this code, use destination option to rename the file.
var upload = multer({
storage: new FTPStorage({
basepath: '/path',
destination: function (req, file, options, callback) {
callback(null, path.join(options.basepath, file.originalname))
},
ftp: {
host: host,
secure: false,
user: user,
password: pwd
}
})
}).single('fileupload');
//corrected code

Multer : Setting different destinations in the destination Property

I have a case where I need to store images in different directories . So I have set the multer as.
app.use(multer({
dest: path.join(__dirname, '`public/assets/img/profile`'),
rename: function (fieldname, filename, req, res) {
if(req.session.user) return req.session.user.id;
else if(req.session.doctor) return req.session.doctor.id;
}
}));
However I need more destinations to store images.
public/assets/img/picture1
I have seen similar questions but I could not understand any of them.
Any help would be greatfull.
Your example is from quite old version of multer. I strongly recommend you to use latest version (due to security reasons).
If you are sure that you need old version then just add to your multer options:
app.use(multer({
//...
changeDest: function(dest, req, res) {
return dest + '/user1';
}
//...
}));
More details you will get in documentation (link to old version) link
Newest version of multer works a little different. This would be to big offtopic to write in detail how to use new version of multer. You easily will find in stackoverflow answer or from actual version of documentation link
I only write how to change destination directory (example from docs):
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, '/tmp/my-uploads')
},
filename: function (req, file, cb) {
cb(null, file.fieldname + '-' + Date.now())
}
})
var upload = multer({ storage: storage })
app.post('/profile', upload.single('picture'), function (req, res, next) {
// req.file is the `picture` file
// req.body will hold the text fields, if there were any
})

Categories

Resources