LoginSignup
9
14

More than 5 years have passed since last update.

Node.jsで画像アップロードと表示

Posted at

Node.jsで画像アップロードを受けつけるサーバーの続きです。
(ちょっと追加しただけです)

index.htmlserver.jsと同じ階層に作ります。アップロードした画像img.jpegがあります。

index.html
<html>
    <head></head>
    <body>
        <img src="/img.jpeg">
    </body>
</html>

コード

app.use(express.static(__dirname));の部分とres.sendFile()を追加しているくらいです。

server.js
'use strict';

const fs = require('fs');
const express = require('express');
const app = express();
const PORT = process.env.PORT || 3000;
app.use(express.static(__dirname));

//画像表示
app.get('/', (req, res) => res.sendFile('./index.thml'));

//画像アップロードを受け付け
app.post('/', (req, res) => {
    let buffers = [];
    let cnt = 0;

    req.on('data', (chunk) => {
        buffers.push(chunk);
        console.log(++cnt);
    });

    req.on('end', () => {
        console.log(`[done] Image upload`);
        req.rawBody = Buffer.concat(buffers);
        //書き込み
        fs.writeFile('./img.jpeg', req.rawBody, 'utf-8',(err) => {
            if(err) return;
            console.log(`[done] Image save`);
        });
    });
});

app.listen(PORT);

実行

$ node server.js

実行して localhost:3000にアクセスすると画像が表示されます。

9
14
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
9
14