如何使用multer在nodejs中调整图像大小

时间:2017-11-23 11:29:50

标签: node.js

Multer已经限制了尺寸属性。此属性仅限制图像。不调整图像大小。我的问题是假设图像大于"限制尺寸",如何调整图像大小?

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

var avatarUpload = multer({
    storage: storageOptions,
    limits: {
        fileSize: 1000000
    }
}).single("avatar");

3 个答案:

答案 0 :(得分:1)

这取决于您是否也要存储已调整大小的图像。

在任何情况下,您都将使用库来处理调整大小操作。 sharp是一个非常好的选择。

在路由处理程序中调整大小(在文件存储到磁盘后):

sharp(req.file).resize(200, 200).toBuffer(function(err, buf) {
  if (err) return next(err)

  // Do whatever you want with `buf`
})

其他选项是创建自己的存储引擎,在这种情况下,您将收到文件数据,调整大小,然后存储到磁盘(从https://github.com/expressjs/multer/blob/master/StorageEngine.md复制):

var fs = require('fs')

function getDestination(req, file, cb) {
  cb(null, '/dev/null')
}

function MyCustomStorage(opts) {
  this.getDestination = (opts.destination || getDestination)
}

MyCustomStorage.prototype._handleFile = function _handleFile(req, file, cb) {
  this.getDestination(req, file, function(err, path) {
    if (err) return cb(err)

    var outStream = fs.createWriteStream(path)
    var resizer = sharp().resize(200, 200).png()

    file.stream.pipe(resizer).pipe(outStream)
    outStream.on('error', cb)
    outStream.on('finish', function() {
      cb(null, {
        path: path,
        size: outStream.bytesWritten
      })
    })
  })
}

MyCustomStorage.prototype._removeFile = function _removeFile(req, file, cb) {
  fs.unlink(file.path, cb)
}

module.exports = function(opts) {
  return new MyCustomStorage(opts)
}

答案 1 :(得分:1)

试试这个代码Resize Image Upload Using Multer

安装 Express 和 Multer 依赖项

npm install express multer --save npm install sharp --save

创建 Server.js 文件

const express = require('express');
const multer = require('multer');
const path = require('path');
const sharp = require('sharp');
const fs = require('fs');
const app = express();
const port = 3000
   
const storage = multer.diskStorage({
    destination: function(req, file, cb) {
        cb(null, 'uploads/');
    },
   
    filename: function(req, file, cb) {
        cb(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname));
    }
});
   
var upload = multer({ storage: storage })
   
app.get('/', (req, res) => {
  res.sendFile(__dirname + '/index.html');
});
   
app.post('/', upload.single('image'),async (req, res) => {
       const { filename: image } = req.file;
       
       await sharp(req.file.path)
        .resize(200, 200)
        .jpeg({ quality: 90 })
        .toFile(
            path.resolve(req.file.destination,'resized',image)
        )
        fs.unlinkSync(req.file.path)
       
       res.redirect('/');
});
   
app.listen(port, () => {
  console.log(`Example app listening at http://localhost:${port}`)
})

创建表单

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Node JS Resize Image Upload Using Multer Sharp With Example - phpcodingstuff.com</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
  </head>
  <body>
    <h1>Node JS Resize Image Upload Using Multer Sharp With Example - phpcodingstuff.com</h1>
    <form action="/" enctype="multipart/form-data" method="post">
      <input type="file" name="image" accept='image/*'>
      <input type="submit" value="Upload">
    </form>  
  </body>
</html>

享受这code

答案 2 :(得分:0)

const path = require("path");
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, path.join(__dirname, "/uploads"));
  },
  filename: function (req, file, cb) {
    cb(null, uuid.v4() + `${path.extname(file.originalname)}`);
  }
});

const limits = {
  fields: 10,
  fileSize: 500 * 1024,
  files: 1,
};

const upload = multer({ storage, limits });
const baseUrl = "http://localhost:3000/files/";
router.post("/upload", upload.single("file"), async (ctx, next) => {
  ctx.body = {
    code: 1,
    data: baseUrl + ctx.file.filename,
  };
});