1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

express + multer + sharpで画像のリサイズ処理をする

Posted at

やりたいこと

アップロードされた時に画像をリサイズして保存する。

構造

tree

nodeApp --- 'node-modules'
        --- 'public/index.html'
        --- 'package.json'
        --- 'server.js'

やる前の準備

npm で sharp を install

terminal
$ npm init

npm init をした時点で package.json ができます。

STEP 1. serverを立てよう

以下のコードをpackage.jsonにコピペしましょう。

package.json
{
  "name": "image-upload",
  "version": "1.0.0",
  "main": "server.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "node server"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "^4.16.3",
    "multer": "^1.3.0",
    "node-inspect": "^1.11.6",
    "sharp": "^0.23.1"
  },
  "devDependencies": {},
  "description": ""
}

以下のコードをserver.jsにコピペします。

server.js
const express = require('express');
const multer = require('multer');
const sharp = require('sharp');

const destDir = 'uploads/images/';

var storage = multer.diskStorage({
    destination: destDir,
    filename: function (req, file, cb) {
        cb(null, file.originalname)
    }
})

const upload = multer({
    storage: storage
});

const app = express();
const PORT = 3000;

app.use(express.static('public'));

app.post('/upload', upload.single('photo'), (req, res) => {
    if (req.file) {
        res.json(req.file);
        sharp(req.file.originalname)
            .resize(64)
            .toFile(destDir + 'resized' + req.file.originalname, (err, info) => {
                if (err) {
                    throw err;
                }
                console.log(info);
            });
        console.log("file: ", req.file);
    } else throw 'error';
});

app.listen(PORT, () => {
    console.log('Listening at ' + PORT);
});

次にpublic/index.htmlを作り、以下のコードをコピペします。

terminal
$ mkdir public && touch index.html
index.html
<!DOCTYPE html>
<html lang="en">

    <head>
        <title>Upload Images to Server</title>
        <meta charset="utf-8">

    </head>

    <body>

        <h1>Upload Image</h1>

        <form action="/upload" method="post" enctype="multipart/form-data">
            <input type="file" accept="image/*" name="photo">
            <input type="submit" value="upload">
        </form>


    </body>

</html>

実行してみましょう。

terminal
$ npm install && npm start

serverが立ち上がったので、もう一つのターミナルを開きましょう。
そしたら,curlコマンドで画像をserverにあげたいと思います。

curlはserverに問い合わせできるものと考えて今は大丈夫です。

terminal
$ curl 'localhost:3000/upload' -X POST -F photo=@cat.jpg

ちなみに、ブラウザで「localhost:3000」を開けば upload ページが出てくるので、そこからも試すことは可能です。

最終的なフォルダの構造

tree

nodeApp --- 'node-modules'
        --- 'public/index.html'
        --- 'uploads/images/resizedcat.jpg
        --- 'package.json'
        --- 'server.js'

お疲れ様です。

参考URL: node server
参考URL: sharp

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?