Saturday 27 May 2017

return filename of uploaded file with multer and nodejs

I am creating a simple application as a learning experience with ionic 2 that connects to a node server running multer to upload images. The problem I am running into is, I need to get the final file name from multer back to the app that uploaded it, to save it locally. I am using the Auth and User modules from @ionic/cloud-angular for authentication and user information. The User object has a details object with things like "name", "email", "username", "image", ... So, when an image is uploaded to the node server and multer saves it, I need to get that filename back to the application so I can update the user.details.image property.

Here is a simple version of my node server...

var express = require('express');
var http = require('http');
var bodyParser = require('body-parser');
var multer = require('multer');
var cors = require('cors');
var postStorage = multer.diskStorage({
    destination: function(req, file, callback) {
        callback(null, './uploads');
    },
    filename: function(req, file, callback) {
        let fileName = '', postName;
        if(typeof req.body.postName !== "undefined") {
            postName = req.body.postName.toLowerCase().replace(/ /g, '-');
            filename += postName;
        }
        fileName += new Date().getTime();
        fileName += ".png";
        callback(null, fileName);
    }
});
var app = express();
app.set('port', process.env.PORT || 3000);
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(cors());
app.post('/upload', function(req, res) {
    var uploadPost = multer({storage: postStorage}).single('post_image');
    uploadPost(req, res, function(err) {
        if(err) {
            return res.end("error uploading file");
        }
        res.end("file uploaded");
    });
});
app.listen(app.get('port');
console.log("app listening on port: " _ app.get('port'));

Is there a way to have it send back the final file name that multer saved? Something like res.json({fileName: fileName}); res.end(); I really don't know at this point, and all the tutorials I can find on multer just show how to create a new filename and save a file in disk or database or memory, but nowhere does it show how you can actually get that filename back to the application that uploaded it. Thank you in advance for any help, I really appreciate it. If you need to see the ionic 2 code that uploads the stuff please let me know and I will update the post with that code as well. Thank you.



via Neglected Sanity

No comments:

Post a Comment