npm install
必要なモジュールをインストール
1 2 |
npm install aws-sdk@2.1001.0 npm install express-form-data@2.0.0 |
express-form-dataは、フォームに入力されたファイルの実体をサーバー側に送信するのに必要。.ejs のフォームに enctype=’multipart/form-data’ が必要
コード(.js)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
const express = require('express'); const router = express.Router(); const fs = require("fs"); const AWS = require('aws-sdk'); const s3 = new AWS.S3({ accessKeyId: "アクセスキー", secretAccessKey: "シークレットアクセスキー", region: 'ap-northeast-1', signatureVersion: 'v4' }); const formData = require('express-form-data'); router.use(formData.parse()); router.get('/', (req, res, next) => { res.render(`index`); }); router.post('/', (req, res, next) => { var inputFile = req.files.inputFile; (async () => { await uploadToS3(); res.redirect(`/index`); })(); async function uploadToS3() { return new Promise(resolve => { var param = { Bucket: "バケット名", Key: "ファイルをアップする場所" + '/' + inputFile.name, Body: fs.createReadStream(inputFile.path), ContentType: inputFile.mimetype } s3.upload(param, function (err, data) { if (err) { return res.status(400).send(err); } resolve(); }); }); } }); module.exports = router; |
コード(.ejs)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
<!DOCTYPE html> <html> <head> <title>S3アップロード</title> <link rel="stylesheet" href="/stylesheets/style.css"> </head> <body> <form method="post" enctype='multipart/form-data'> <input type="file" accept="*" name="inputFile"> <input class="btn1" type="submit" value="S3にアップロード"> </form> </body> </html> |