在Express.js

时间:2017-06-13 17:12:37

标签: javascript node.js express file-upload

在我的应用中,我正在public / images文件夹中上传一些图片。以前一切都很好,但现在不行了。我收到了一条成功消息,意味着图片已上传到文件夹中,但是,我看不到它:(。这就是邮递员给我的回复。(POST = http://localhost:3000/image )。

    {
     "success": true,
     "message": "Image uploaded!"
    }

这有点奇怪。一切似乎都是正确的。这是我的代码。

imageRouter

        var express = require('express');
        var imageRouter = express.Router();
        var multer = require('multer');

        var storage = multer.diskStorage({
            destination: function (req, file, cb) {
                cb(null, './public/images')
            },
            filename: function (req, file, cb) {
                cb(null, file.fieldname + '-' + Date.now() + '.jpg')
            }
        });

        var upload = multer({ storage: storage }).single('myImage');



        imageRouter.post('/', function (req, res) {
            upload(req, res, function (err) {
                if (err) {
                    // An error occurred when uploading
                }
                res.json({
                    success: true,
                    message: 'Image uploaded!'
                });

                // Everything went fine
            })
        });


        module.exports = imageRouter;

app.js

var express = require('express');
            var path = require('path');
            var favicon = require('serve-favicon');
            var logger = require('morgan');
            var cookieParser = require('cookie-parser');
            var bodyParser = require('body-parser');
            var mongoose = require('mongoose');
            var url = 'mongodb://localhost:27017/larissaApp';

            mongoose.connect(url);
            var db = mongoose.connection;
            db.on('error',console.error.bind(console,'connection error:'));
            db.once('open',function(){
               console.log("Connected correctly to server"); 
            });

            var routes = require('./routes/index');
            var users = require('./routes/users');
            var newsRouter = require('./routes/newsRouter');
            var cityRouter = require('./routes/cityRouter');
            var imageRouter = require('./routes/imageRouter');
            var mayorRouter = require('./routes/mayorRouter');
            var deputyMayorRouter = require('./routes/deputyMayorRouter');
            var app = express();
            // view engine setup
            app.set('views', path.join(__dirname, 'views'));
            app.set('view engine', 'jade');
            // uncomment after placing your favicon in /public
            //app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
            app.use(logger('dev'));

            app.use(bodyParser.urlencoded({ extended: false }));
            app.use(cookieParser());
            app.use('/public', express.static(path.join(__dirname, 'public')));

            app.use('/', routes);
            app.use('/users', users);
            app.use('/news',newsRouter);
            app.use('/news',newsRouter);
            app.use('/city',cityRouter);
            app.use('/image',imageRouter);
            app.use('/mayor',mayorRouter);
            app.use('/deputymayor',deputyMayorRouter);
            // catch 404 and forward to error handler
            app.use(function(req, res, next) {
              var err = new Error('Not Found');
              err.status = 404;
              next(err);
            });
            // error handlers
            // development error handler
            // will print stacktrace
            if (app.get('env') === 'development') {
              app.use(function(err, req, res, next) {
                res.status(err.status || 500);
                res.render('error', {
                  message: err.message,
                  error: err
                });
              });
            }
            // production error handler
            // no stacktraces leaked to user
            app.use(function(err, req, res, next) {
              res.status(err.status || 500);
              res.render('error', {
                message: err.message,
                error: {}
              });
            });
            module.exports = app;

服务器侦听部分位于我的 bin / www 文件中。

最后我使用 expreess-4.15.2

有什么想法吗?

谢谢,

西奥。

1 个答案:

答案 0 :(得分:1)

由于您没有使用returnPOST /image路由处理程序中停止执行,因此无论结果如何,您总是会成功响应。只需在发生错误时返回响应,您就会停止获得每个结果的成功响应。

imageRouter.post('/', (req, res) => {
    upload(req, res, err => {
        if (err) {
            // An error occurred when uploading
            return res.sendStatus(500)
        }

        // Everything went fine
        return res.json({
            success: true,
            message: 'Image uploaded!'
        });
    })
});