Почему изображение не загружено в node.js?

Я изучаю node.js и пытаюсь создать простое приложение для загрузки изображений, используя Express и Multer, чтобы загрузить одно изображение, переименовать и сохранить его.

Вот соответствующие части:

app.use(multer({dest:'/home/pc/node-dev/mypapp/public/upload/temp'}).single('file'));

Форма:

<form method="post" action="/images" enctype="multipart/form-data">

            <input class="form-control" type="file" name="file">

                <textarea class="form-control" name="description" rows="2"></textarea>

                <button type="submit" id="login-btn" class="btn btn-success" type="button">Upload Image</button>

</form>

в в ‍‍images.js Я имею::

 create: function(req, res) {
            var saveImage = function() {
                console.log('saving image');
                console.log(req.body);
                console.log(req.file.path);
                var possible = 'abcdefghijklmnopqrstuvwxyz0123456789',
                    imgUrl = '';

                for(var i=0; i < 6; i+=1) {
                    imgUrl += possible.charAt(Math.floor(Math.random() * possible.length));
                }

                var tempPath = req.file.path,
                    ext = path.extname(req.file.name).toLowerCase(),
                    targetPath = path.resolve('/home/pc/node-dev/myapp/public/upload/' + imgUrl + ext);
                    console.log('imgUrl is %s', imgUrl );
                    console.log('targetPath is %s', targetPath );
                    console.log('filename is %s', req.file.name );
                    console.log('ext is %s', ext );

                if (ext === '.png' || ext === '.jpg' || ext === '.jpeg' || ext === '.gif') {


                    fs.rename(tempPath, targetPath, function(err) {
                        if (err) throw err;

                        res.redirect('/images/' + imgUrl);
                    });
                } else {
                    fs.unlink(req.file.path, function () {
                        console.log(req.file.path);

                        res.json(500, {error: 'Only image files are allowed.'});
                    });
                }
            };

Результат, который я получаю в консоли:

saving image
{ title: 'ddd', description: 'adwefw' }
/home/pc/node-dev/myapp/public/upload/temp/5b43a0abf25d9b05cf902d64b051a307
imgUrl is 6dnfws
targetPath is /home/pc/node-dev/myapp/public/upload/6dnfws
filename is undefined
ext is 

и в браузере эта страница отображается:

{"error":"Only image files are allowed."}

Так что с одной стороны, есть req.file.pathС другой стороны, видимо, нет req.file.name,

Я действительно смущен этим, поэтому цените ваши намеки.

1 ответ

Тебе нужно originalname (имя файла на компьютере пользователя):

ext = path.extname(req.file.originalname).toLowerCase()

https://github.com/expressjs/multer

Другие вопросы по тегам