2
0

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 3 years have passed since last update.

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

Last updated at Posted at 2021-06-12

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
**

2
0
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
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?