Quantcast
Channel: Node.jsタグが付けられた新着記事 - Qiita
Viewing all articles
Browse latest Browse all 8883

Node.js(Express)を使用してCloudinaryに画像をアップロード・更新する

$
0
0
Cloudinaryに画像をアップするには、まずはcloudinaryとmulterをインストールします。 npm i cloudinary multer 続いてCloudinaryのWebサイトにログインし、ダッシュボードのアカウント詳細欄にある「クラウド名・APIキー・APIシークレット」の値をコピーする。そして.envファイルを作成し、それぞれの変数にコピーした値を代入します。 .env CLOUD_NAME=クラウド名 API_KEY=APIキー API_SECRET=APIシークレット 今度はutilsフォルダーを作成し、このフォルダー内にcloudinary.jsとmulter.jsファイルを作成します。 それぞれのファイルの中身は次のようになります。 cloudinary.js const cloudinary = require("cloudinary").v2; cloudinary.config({ cloud_name: process.env.CLOUD_NAME, api_key: process.env.API_KEY, api_secret: process.env.API_SECRET, }); module.exports = cloudinary; multer.js const multer = require("multer"); const path = require("path"); // Multer config module.exports = multer({ storage: multer.diskStorage({}), fileFilter: (req, file, cb) => { let ext = path.extname(file.originalname); if (ext !== ".jpg" && ext !== ".jpeg" && ext !== ".png") { cb(new Error("File type is not supported"), false); return; } cb(null, true); }, }); 2つのファイルの記述が終わったらindex.jsに移動し、ファイルのパスを作成します。 index.js app.use('/user', require('./routes/user')) 上で通したパスのファイルを作成します。routesフォルダーを作成し、その中にuser.jsファイルを作成します。ファイルの中は、以下の通りです。 user.js const router = require("express").Router(); const cloudinary = require("../utils/cloudinary"); const upload = require("../utils/multer"); const User = require("../model/user"); router.post("/", upload.single("image"), async (req, res) => { try { // Upload image to cloudinary const result = await cloudinary.uploader.upload(req.file.path); // Create new user let user = new User({ name: req.body.name, avatar: result.secure_url, cloudinary_id: result.public_id, }); // Save user await user.save(); res.json(user); } catch (err) { console.log(err); }}); module.exports = router; cloudinary.uploader.uploadを画像をアプロードする記述になります。cloudinaryから帰ってきたレスポンスにはsecure_urlとpublic_idが含まれているので、avatarとcloudinary_idに保存します。 cloudinaryにアップしている画像を更新するにはputではなく、cloudinary_idを指定して削除し、再度アップする処理が必要となります。 具体的には次のようになります。 // まずcloudinary上の画像を指定して削除 cloudinary.uploader.destroy(user.cloudinary_id) // 再度画像をアップロード cloudinary.uploader.upload() これでNode.jsからCloudinaryへの画像のアップロード・更新は完璧です! 参照 https://dev.to/itsmefarhan/cloudinary-files-images-crud-operations-with-nodejs-express-multer-2147 **

Viewing all articles
Browse latest Browse all 8883

Trending Articles