使用 multer 和 node.js 在云存储上上传不同类型的文件

问题描述 投票:0回答:1

我正在尝试将文件从不同的字段上传到我的云存储。它适用于图像上传。但是,当我尝试上传视频时,出现错误:POST http://localhost:3000/create-post 500(内部服务器错误)。 这是 ejs 表单

<form action="/create-post" method="POST" enctype="multipart/form-data">
  <div class="mb-3">
    <label for="postImage" class="form-label">Upload Image</label>
    <input type="file" class="form-control" id="postImage" name="postImage">
  </div>
  <div class="mb-3">
    <label for="postVideoFile" class="form-label">Upload Video (Max size: 20MB)</label>
    <input type="file" class="form-control" id="postVideoFile" name="postVideo">
  </div>
  <button type="submit" class="btn btn-primary">Create Post</button>
</form>

控制器,

const Post = require('../models/Post');
const cloudinary = require('../utils/cloudinary');

exports.createPost = async (req, res) => {
  try {
    const { postCaption, postLink, postEmbeddedVideo } = req.body;
    const user = req.user._id; // Assuming you have user information in req.user

    const post = new Post({
      postCaption,
      postLink,
      postEmbeddedVideo,
      user,
    });

    if (req.file) {
      if (req.file.mimetype.startsWith('image')) {
        // Upload images to Cloudinary
        const imageResult = await cloudinary.uploader.upload(req.file.path, {
          resource_type: 'image',
        });
        post.postImage = imageResult.secure_url;
      } else if (req.file.mimetype.startsWith('video')) {
        // Upload videos to Cloudinary
        const videoResult = await cloudinary.uploader.upload(req.file.path, {
          resource_type: 'video',
        });
        post.postVideo = videoResult.secure_url;
      }
    }

    await post.save();

    res.status(201).json({ message: 'Post created successfully', post });
  } catch (error) {
    res.status(500).json({ message: 'Error creating post', error: error.message });
  }
};

发布模型,

const mongoose = require('mongoose');

const postSchema = new mongoose.Schema({
  postCaption: String,
  postImage: String,
  postVideo: String,  
  postLink: String,
  postEmbeddedVideo: String,
  user: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'User'
  }
});

module.exports = mongoose.model('Post', postSchema);

路线处理程序,

router.post('/create-post', authMiddleware, upload.fields([{ name: 'postImage', maxCount: 1 }, { name: 'postVideo', maxCount: 1 }]), postController.createPost);

multer 中间件,

const multer = require('multer');
const { CloudinaryStorage } = require('multer-storage-cloudinary');
const cloudinary = require('cloudinary').v2;

const storage = new CloudinaryStorage({
  cloudinary: cloudinary,
  params: {
    folder: 'uploads', // Optional: set the folder in Cloudinary where you want to store the files
    allowedFormats: ['jpg', 'png', 'gif', 'mp4'],
  },
});

const upload = multer({ storage: storage });

module.exports = { upload };

我还在表单中使用一个脚本,如果上传图像,该脚本将禁用视频输入字段,反之亦然。当我上传图像时,它就会被上传。我想上传一个视频,获取它的 url 并将该 url 保存到我的数据库中以便稍后访问。但是,我无法上传视频。正如您所看到的,我已经提到了允许的格式(mp4),并指定了资源类型。据我所知,upload.fields 的语法也是正确的。

node.js multer cloudinary
1个回答
0
投票

我怀疑由于 Multer 配置的原因,这是先上传文件,然后控制器中的代码再进行一次上传。当您上传视频时,Multer 对 Cloudinary 的上传请求失败,从而引发错误,因此它也不会到达您的控制器代码。如果是这种情况,您应该会在 Cloudinary 媒体库中看到每个上传图像的重复图像。

默认情况下,上传到 Cloudinary 时,除非明确指定,否则

resource_type
默认为
image
,因此当您上传视频时,很可能实际上是将
resource_type: "image"
发送到 Cloudinary,因此上传失败。

在您的 Multer 配置中 (

CloudinaryStorage
=>
params
),您可以尝试添加:

resource_type: "auto"

const storage = new CloudinaryStorage({
  cloudinary: cloudinary,
  params: {
    resource_type: "auto",
    folder: 'uploads', // Optional: set the folder in Cloudinary where you want to store the files
    allowedFormats: ['jpg', 'png', 'gif', 'mp4'],
  },
});

这将确保 Cloudinary 可以根据上传的文件自动分配

resource_type
,而不是默认为“图像”。

© www.soinside.com 2019 - 2024. All rights reserved.