javascript - URL to file which was uploaded with Multer -


i using multer upload files , wondering recommended way access files after upload.

this 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 uploaded");     }); } 

accessing following url localhost:8000/uploads/teacher/uploaded_file_name.png gives error error: not found.

you need create public folder static assets (including uploads). folder structure ./public/uploads/teacher/.

then must update 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 following line server.js serve static resources public dir:

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

you should able access localhost:8000/uploads/teacher/uploaded_file_name.png


Comments