- 1. 概要
- 2. インストール
- 3. 準備
- 4. ソース作成
- 5. 確認
- 6. 参考サイト
1. 概要
事情があって、アップロード機能をつけたかったのです。
2. インストール
プロジェクトの管理者権限で、プロジェクトのドキュメントルートで。
npm install multer
added 11 packages, and audited 160 packages in 4s
26 packages are looking for funding
run 'npm fund' for details
1 moderate severity vulnerability
To address all issues, run:
npm audit fix
Run 'npm audit' for details.
npm notice
npm notice New patch version of npm available! 11.6.2 -> 11.6.4
npm notice Changelog: https://github.com/npm/cli/releases/tag/v11.6.4
npm notice To update run: npm install -g npm@11.6.4
npm notice
たまたま、アップグレードが発生していたようです。
3. 準備
アップロード用のディレクトリを作成します。
プロジェクトのドキュメントルートで。
「root」ユーザ権限で。
mkdir -pv uploads
chmod 755 uploads
4. ソース作成
プロジェクトのドキュメントルートへ移動して、プロジェクト管理者権限で。
vi server.js
下記を記述します。
const express = require("express");
const multer = require("multer");
const path = require("path");
const app = express();
// 保存先とファイル名の設定
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, "uploads/"); // 保存フォルダ
},
filename: (req, file, cb) => {
cb(null, Date.now() + path.extname(file.originalname));
}
});
const upload = multer({ storage: storage });
const port = 3000;
app.use(express.json());
// public フォルダを静的配信
app.use(express.static('public'));
// 単一ファイル upload
app.post("/upload", upload.single("file"), (req, res) => {
console.log(req.file); // アップロードされたファイル情報
res.json({ message: "アップロード完了", file: req.file });
});
app.listen(port, () => {
console.log("Server started on port 3000");
});
コンテンツファイルを作成します。
vi public/index.html
下記を記述します。
<!DOCTYPE html>
<html>
<head></head>
<body>
<form action="/upload" method="post" enctype="multipart/form-data">
<input type="file" name="file">
<button type="submit">アップロード</button>
</form>
</body>
|