Как изменить размер изображения в nodejs, используя 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 ответа

Это зависит от того, хотите ли вы сохранить измененное изображение.

В любом случае вы будете использовать библиотеку для обработки операции изменения размера. Острый это очень хороший вариант.

Изменение размера в обработчике маршрута (после сохранения файла на диске):

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)
}

Попробуйте этот код

Установите Express и Multer Dependencies

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>

Наслаждайтесь этим Изменить размер изображения при загрузке с помощью Multerкодом

      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,
  };
});
Другие вопросы по тегам