【问题标题】:How to resize image size in nodejs using multer如何使用 multer 在 nodejs 中调整图像大小
【发布时间】:2018-05-07 08:37:05
【问题描述】:

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");

【问题讨论】:

    标签: node.js


    【解决方案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)
    }

    【讨论】:

    • "sharp Module" 无法安装,因为 cmd 抛出以下错误 sharp@0.18.4 install: node-gyp rebuild Exit status 1 Failed at the sharp@0.18.4 install script 'node-gyp rebuild' .
    • 如果最后一行输出没问题,那就没问题
    • @AndréWerlang 嗨,我知道这个答案已经有一段时间了,但请你看看我的问题。stackoverflow.com/questions/65465145/…
    【解决方案2】:

    试试这个代码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

    【讨论】:

      【解决方案3】:
      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,
        };
      });
      

      【讨论】:

      • 点评来源: 您好,在 Stack Overflow 上不鼓励仅代码或仅命令的答案,因为它们没有解释它如何解决问题。请编辑您的答案以解释此代码的作用以及它如何回答问题,以便对有类似问题的人有用。请参阅:How do I write a good answer?
      猜你喜欢
      • 2019-05-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-30
      • 1970-01-01
      • 2019-11-07
      相关资源
      最近更新 更多