Ad

URL To File Which Was Uploaded With Multer

- 1 answer

I am using Multer to upload some files and I am wondering what would be the recommended way to access those files after upload.

This is my code:

server.js

app.use('/', require('./routes'));

routes/index.js

var teacher = require('./teachers.js');

router.post('/upload', teacher.uploadAvatar);

routes/teachers.js

var multer      = require('multer');
var upload      = multer({ dest: 'uploads/teacher/' }).single('avatar');

uploadAvatar: function(req, res) {
    upload(req, res, function(err) {
        console.log(req.body);
        console.log(req.file);

        if(err) {
            return res.end("Error uploading file.");
        }
        res.end("File is uploaded");
    });
}

Accessing the following Url localhost:8000/uploads/teacher/uploaded_file_name.png gives error Error: Not Found.

Ad

Answer

You need to create a public folder for static assets (including uploads). So your folder structure will then look like ./public/uploads/teacher/.

Then you must update the following line in routes/teachers.js from:

var upload      = multer({ dest: 'uploads/teacher/' }).single('avatar');

to:

var upload      = multer({ dest: 'public/uploads/teacher/' }).single('avatar');

And add the following line to your server.js to serve static resources from the public dir:

app.use(express.static('public'));

You should then be able to access localhost:8000/uploads/teacher/uploaded_file_name.png

Ad
source: stackoverflow.com
Ad