📌  相关文章
📜  如何使用 node.js 将单个/多个图像上传到 cloudinary?

📅  最后修改于: 2022-05-13 01:56:51.654000             🧑  作者: Mango

如何使用 node.js 将单个/多个图像上传到 cloudinary?

Cloudinary是针对网站和移动应用程序的端到端图像和视频管理解决方案,涵盖从图像和视频上传、存储、操作、优化到交付的所有内容。

安装:

  • 步骤 1:进入项目目录并在终端中使用以下命令初始化项目。

    npm init -y
  • 第 2 步:使用以下命令安装所需的 npm 包。

    npm install express multer cloudinary
  • 第 3 步:在当前项目目录中创建 2 个文件,分别命名为index.jspublic/index.html ,如下面的项目目录所示。

项目结构:

index.html:它基本上包含两种形式,即单文件上传和多文件上传。

index.html


    
        
                                  
        
                     
    
           


       
        
                                  
        
                     
    


index.js
// Requiring module
const express = require("express");
const multer = require("multer");
const port = 3000;
const app = express();
const cloudinary = require("cloudinary").v2;
const bodyParser = require("body-parser");
const fs = require("fs");
  
// Creating uploads folder if not already present
// In "uploads" folder we will temporarily upload
// image before uploading to cloudinary
if (!fs.existsSync("./uploads")) {
    fs.mkdirSync("./uploads");
}
  
// Multer setup
var storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, "./uploads");
    },
    filename: function (req, file, cb) {
        cb(null, file.originalname);
    },
});
  
var upload = multer({ storage: storage });
  
// Body parser configuration
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
  
app.use(express.static(__dirname + "/public"));
app.use("/uploads", express.static("uploads"));
  
// Cloudinary configuration
cloudinary.config({
    cloud_name: "YOUR_CLOUD_NAME",
    api_key: "YOUR_API_NAME",
    api_secret: "YOUR_API_SECRET",
});
  
async function uploadToCloudinary(locaFilePath) {
  
    // locaFilePath: path of image which was just
    // uploaded to "uploads" folder
  
    var mainFolderName = "main";
    // filePathOnCloudinary: path of image we want
    // to set when it is uploaded to cloudinary
    var filePathOnCloudinary = 
        mainFolderName + "/" + locaFilePath;
  
    return cloudinary.uploader
        .upload(locaFilePath, { public_id: filePathOnCloudinary })
        .then((result) => {
  
            // Image has been successfully uploaded on
            // cloudinary So we dont need local image 
            // file anymore
            // Remove file from local uploads folder
            fs.unlinkSync(locaFilePath);
  
            return {
                message: "Success",
                url: result.url,
            };
        })
        .catch((error) => {
  
            // Remove file from local uploads folder
            fs.unlinkSync(locaFilePath);
            return { message: "Fail" };
        });
}
  
function buildSuccessMsg(urlList) {
  
    // Building success msg to display on screen
    var response = `

                   Click to go to Home page
                  


`;        // Iterating over urls of images and creating basic     // html to render images on screen     for (var i = 0; i < urlList.length; i++) {         response += "File uploaded successfully.

";         response += `FILE URL:                     ${urlList[i]}.

`;         response += `

`;     }        response += `

Now you can store this url in database or    // do anything with it  based on use case.

`;     return response; }    app.post(     "/profile-upload-single",     upload.single("profile-file"),     async (req, res, next) => {            // req.file is the `profile-file` file         // req.body will hold the text fields,         // if there were any            // req.file.path will have path of image         // stored in uploads folder         var locaFilePath = req.file.path;            // Upload the local image to Cloudinary          // and get image url as response         var result = await uploadToCloudinary(locaFilePath);            // Generate html to display images on web page.         var response = buildSuccessMsg([result.url]);            return res.send(response);     } );    app.post(     "/profile-upload-multiple",     upload.array("profile-files", 12),     async (req, res, next) => {            // req.files is array of `profile-files` files         // req.body will contain the text fields,         // if there were any         var imageUrlList = [];            for (var i = 0; i < req.files.length; i++) {             var locaFilePath = req.files[i].path;                // Upload the local image to Cloudinary             // and get image url as response             var result = await uploadToCloudinary(locaFilePath);             imageUrlList.push(result.url);         }            var response = buildSuccessMsg(imageUrlList);            return res.send(response);     } );    app.listen(port, () => {     console.log(`Server running on port ${port}!             \nClick http://localhost:3000/`); });


index.js:cloud_nameapi_keyapi_secret替换为您可以在 cloudinary 仪表板上找到的cloudinary 凭据

index.js

// Requiring module
const express = require("express");
const multer = require("multer");
const port = 3000;
const app = express();
const cloudinary = require("cloudinary").v2;
const bodyParser = require("body-parser");
const fs = require("fs");
  
// Creating uploads folder if not already present
// In "uploads" folder we will temporarily upload
// image before uploading to cloudinary
if (!fs.existsSync("./uploads")) {
    fs.mkdirSync("./uploads");
}
  
// Multer setup
var storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, "./uploads");
    },
    filename: function (req, file, cb) {
        cb(null, file.originalname);
    },
});
  
var upload = multer({ storage: storage });
  
// Body parser configuration
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
  
app.use(express.static(__dirname + "/public"));
app.use("/uploads", express.static("uploads"));
  
// Cloudinary configuration
cloudinary.config({
    cloud_name: "YOUR_CLOUD_NAME",
    api_key: "YOUR_API_NAME",
    api_secret: "YOUR_API_SECRET",
});
  
async function uploadToCloudinary(locaFilePath) {
  
    // locaFilePath: path of image which was just
    // uploaded to "uploads" folder
  
    var mainFolderName = "main";
    // filePathOnCloudinary: path of image we want
    // to set when it is uploaded to cloudinary
    var filePathOnCloudinary = 
        mainFolderName + "/" + locaFilePath;
  
    return cloudinary.uploader
        .upload(locaFilePath, { public_id: filePathOnCloudinary })
        .then((result) => {
  
            // Image has been successfully uploaded on
            // cloudinary So we dont need local image 
            // file anymore
            // Remove file from local uploads folder
            fs.unlinkSync(locaFilePath);
  
            return {
                message: "Success",
                url: result.url,
            };
        })
        .catch((error) => {
  
            // Remove file from local uploads folder
            fs.unlinkSync(locaFilePath);
            return { message: "Fail" };
        });
}
  
function buildSuccessMsg(urlList) {
  
    // Building success msg to display on screen
    var response = `

                   Click to go to Home page
                  


`;        // Iterating over urls of images and creating basic     // html to render images on screen     for (var i = 0; i < urlList.length; i++) {         response += "File uploaded successfully.

";         response += `FILE URL:                     ${urlList[i]}.

`;         response += `

`;     }        response += `

Now you can store this url in database or    // do anything with it  based on use case.

`;     return response; }    app.post(     "/profile-upload-single",     upload.single("profile-file"),     async (req, res, next) => {            // req.file is the `profile-file` file         // req.body will hold the text fields,         // if there were any            // req.file.path will have path of image         // stored in uploads folder         var locaFilePath = req.file.path;            // Upload the local image to Cloudinary          // and get image url as response         var result = await uploadToCloudinary(locaFilePath);            // Generate html to display images on web page.         var response = buildSuccessMsg([result.url]);            return res.send(response);     } );    app.post(     "/profile-upload-multiple",     upload.array("profile-files", 12),     async (req, res, next) => {            // req.files is array of `profile-files` files         // req.body will contain the text fields,         // if there were any         var imageUrlList = [];            for (var i = 0; i < req.files.length; i++) {             var locaFilePath = req.files[i].path;                // Upload the local image to Cloudinary             // and get image url as response             var result = await uploadToCloudinary(locaFilePath);             imageUrlList.push(result.url);         }            var response = buildSuccessMsg(imageUrlList);            return res.send(response);     } );    app.listen(port, () => {     console.log(`Server running on port ${port}!             \nClick http://localhost:3000/`); });

运行程序的步骤:

node index.js

输出:打开浏览器并访问http://localhost:3000 。您现在可以看到以下两种形式,即单张和多张图片上传,如下所示。

参考资料:https://cloudinary.com/documentation/node_integration。