如何使用NodeJ上传图像?

时间:2019-04-16 12:40:36

标签: node.js multer

我想使用Node Js上传产品图像。所以我用multer上传图片。我用邮递员测试了它是否正常工作,但是返回了Please upload a file。我更改了另一张图片,然后显示为PayloadTooLargeError: request entity too large

Unable to detect image

ayloadTooLarge

我的代码

const express = require("express");
const router = express.Router();

const multer = require('multer');
const storage = multer.diskStorage(
{
    destination: function(req, file, cb)
    {
        cb(null, './uploads/');
    },
    filename: function(req, file, cb)
    {
        cb(null, new Date().toISOString() + file.originalname);
    }
});

const fileFilter = (req, file, cb) =>
{
    // reject a file
    if (file.mimetype === 'image/jpeg' || file.mimetype === 'image/png')
    {
        cb(null, true);
    }
    else
    {
        cb(null, false);
    }
};

const upload = multer(
{
    storage: storage,
    limits:
    {
        fileSize: 1024 * 1024 * 50
    },
    fileFilter: fileFilter
});


router.post("/upload", upload.single('productImage'), (req, res, next) =>
{
    if (!req.file)
      return res.send('Please upload a file')
    var tempPath = req.file.path
      console.log(tempPath);
});

package.json

{
  "name": "api",
  "version": "1.0.0",
  "description": "testing version",
  "main": "server.js",
  "dependencies": {
    "express": "^4.16.4",
    "multer": "^1.3.0",
    "nodemon": "^1.18.10",
  },
  "devDependencies": {},
  "scripts": {
    "test": "node server.js",
    "start": "nodemon server.js"
  },
  "keywords": [
    "api"
  ],
  "author": "tteam",
  "license": "ISC"
}

3 个答案:

答案 0 :(得分:1)

您的代码运行正常,我只需要将upload.single('productImage')更改为upload.single('image'),就不会遇到像Please upload a file这样的错误,这是我的笔,它与您的笔和工作方式相同很好。

https://codepen.io/khanChacha/pen/rbJjYj

Please upload a file仅在您不选择任何文件或选择错误的文件类型时发生

我已经更新了您的代码,并做了一些更改,现在可以在这里检查它了。

https://github.com/faiz1996khan/uploads

答案 1 :(得分:0)

  

错误:ENOENT:没有这样的文件或目录,请打开'C:\ Users \ ttest \ Downloads \ Compressed \ uploads-master \ api \ routes \ uploads \ 2019-04-18T14:02:45.456Z55460132_25_63992_n(1)。 jpg'

我认为问题似乎与您存储上载文件的位置有关。存储文件之前,您需要检查upload/是否存在。

user.js

const path = require('path');
const fs = require('fs-extra');

let UPLOAD_LOCATION = path.join(__dirname, 'uploads');
fs.mkdirsSync(UPLOAD_LOCATION); //create `uploads/` folder, if it doesn't exists

使用此位置存储上传文件

const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, UPLOAD_LOCATION);
  },
  filename: function (req, file, cb) {
    cb(null, new Date().toISOString() + file.originalname);
  }
});

作为参考,您可以检查how to configure upload path in multer

答案 2 :(得分:0)

在将字符串转换为字符串后,只需在前端将图像中的字符串转换为文件即可轻松存储文件

使用您的api中的此代码将图片转换为base64字符串,也不要忘记从上传文件夹中删除文件

"img": new Buffer.from(fs.readFileSync(req.file.path)).toString("base64")

删除文件

let resultHandler = function (err) {
    if (err) {
        console.log("unlink failed", err);
    } else {
        console.log("file deleted");
    }
}
fs.unlink(req.file.path, resultHandler);

在您的路线上导入multer

const multer = require('multer');
const upload = multer({ dest: __dirname + '/uploads/images' });`

在您的请求中添加upload.single('img'):

router.post(
    '/fellows-details',
    authorize([Role.ADMIN, Role.USER]), 
    upload.single('img'),
    usersController.fellowsdetails
);

如果您不使用unlink函数,则会导致错误,因为它首先将buffer值存储在文件夹中,然后将其转换为base64