使用Multer上传的文件的URL

时间:2016-01-25 02:47:42

标签: javascript node.js multer

我正在使用Multer上传一些文件,我想知道上传后访问这些文件的推荐方法是什么。

这是我的代码:

server.js

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

路由/ index.js

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

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

路由/ 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");
    });
}

访问以下网址localhost:8000/uploads/teacher/uploaded_file_name.png会出现错误Error: Not Found

1 个答案:

答案 0 :(得分:2)

您需要为public资产(包括上传)创建static文件夹。因此,您的文件夹结构将显示为./public/uploads/teacher/

然后,您必须更新routes/teachers.js中的以下行:

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

为:

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

并将以下行添加到server.js以提供public目录中的静态资源:

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

然后,您应该可以访问localhost:8000/uploads/teacher/uploaded_file_name.png