使用Node.js将图片上传到Cloudinary
开发人员在媒体上传过程中面临的主要问题之一是快速处理图像和视频并进行交付优化。这可以通过使用人工智能(AI)来解决,它不仅可以做到这两点,而且还可以使这个过程自动化。Cloudinary是这种服务的一个好例子。
你可以在自定义网站、本地(使用Node.js或Django)或Cloudinary网页上远程访问和上传图片到Cloudinary服务器。
Cloudinary支持许多语言格式,如Ruby、PHP(v1和v2)、Python、Node.js、Java、.NET、iOS,甚至是Android。
Cloudinary SDKs
| 客户端SDK | 服务器端SDK | 移动SDK |
|---|---|---|
| React | PHP SDK | 安卓 |
| Angular | Ruby on Rails | 脚本语言(Kotlin |
| Vue.js | Django | 脚本 |
| 脚本 | 棋 | - |
| 淘宝网 | 爪哇 | |
| - | Node.js | - |
| - | .Net | - |
在本教程中,我们将学习如何使用Node.js上传图片到Cloudinary。
主要收获
在本教程结束时,你将了解到。
- 开始使用Cloudinary.js。
- 在Node.js应用程序中集成Cloudinary.js。
- 将图片上传到Cloudinary。
前提条件
本教程的基本要求是。
- 网络开发基础知识。
- 在机器上安装一个基本的IDE。在我们的案例中,我们将使用Visual Studio Code(免费,易于使用,而且非常高效)。
- Node.js基础知识。
- 一个稳定的互联网连接。
创建一个账户
Cloudinary为开发者提供了一个免费账户选项。 一旦创建,就进入下一个步骤。
设置我们的项目
创建一个名为Cloudinary-uploader的新目录。在该文件夹中,创建两个新文件,分别为index.js 和.env 。打开你的文件夹,在你的IDE中查看。
打开一个集成终端,在该文件夹内运行npm init -y ,以快速创建package.json 文件。为我们的项目安装所需的库。
这些将包括。
- nodemon
- cloudinary
- formidable
- dotenv
- 表达
formidable.js库是为了专注于视频和图片的上传和编码。它用于解析表单数据,主要是文件上传。
要一次性安装,请运行。
npm i nodemon cloudinary dotenv formidable express
npm i nodemon cloudinary dotenv formidable express
dotenv.js库将使我们能够轻松快速地从本地存储的.env文件中加载环境变量到
process.env。
这将为在任何Node.js项目中使用API名称和密钥提供安全保障,因为它们被存储在远离主进程的地方,并且只有在需要时才会使用。它使用"十二因素应用"方法提供安全保障。
一旦完成,你可以通过在集成终端运行npm update ,更新任何最初安装的软件包。
文件夹结构
我们的文件夹结构如下图所示。
├── node_modules (folder)
├── .env (file)
├── package.json (file)
└── index.js (file)
配置软件包.json
打开我们的package.json 文件,在 "脚本 "部分,添加start 和dev ,如下面的代码所示。
{
"name": "Cloudinary-uploader-Node.js",
"version": "1.0.0",
"description": "In this repository, you will find code that will enable you to easily upload your images to Cloudinary. It is under MIT License. You can clone and modify it for your use.",
"main": "index.js",
"scripts": {
"start": "node index.js",
"dev": "nodemon index.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
"repository": {
"type": "git",
"url": "git+https://github.com/RisoriTofa/Cloudinary-uploader-Node.js.git"
},
"keywords": [],
"author": "",
"license": "ISC",
"bugs": {
"url": "https://github.com/RisoriTofa/Cloudinary-uploader-Node.js/issues"
},
"homepage": "https://github.com/RisoriTofa/Cloudinary-uploader-Node.js#readme",
"dependencies": {
"cloudinary": "^1.25.1",
"dotenv": "^8.2.0",
"express": "^4.17.1",
"formidable": "^1.2.2",
"nodemon": "^2.0.7"
}
}
package.json 文件中的脚本将指定自定义脚本,人们可以使用npm 。
如果你想做一些单元测试,你可以在'test'脚本下指定测试框架。
你可以通过运行Node.js来运行index.js 文件。
node index.js
或者通过运行nodemon。
nodemon run dev
如果你从版本库中获得代码,它将添加额外的版本库配置,表明代码来自哪里,以及在哪里报告任何出现的问题。
设置我们的起点
在index.js 文件中,我们将按顺序进行以下工作。
- 本项目需要的模块。
这些都显示在下面的代码中。
// Required modules
const http = require('http');
const util = require('util');
// https://github.com/node-formidable/node-formidable
const Formidable = require('formidable');
//https://www.npmjs.com/package/dotenv
const cloudinary = require("cloudinary");
require('dotenv').config()
- 设置我们的Cloudinary配置。在其中,我们将设置存储在
.env文件中的三个参数。这些参数包括云名称(CLOUD_NAME),我们的API密钥(API_KEY),和API秘密(API_SECRET)。
这在下面的代码中显示。
// Cloudinary configuration settings
// This will be fetched from the .env file in the root directory
cloudinary.config({
cloud_name: process.env.CLOUD_NAME,
api_key: process.env.API_KEY,
api_secret: process.env.API_SECRET
});
- 我们将创建一个简单的Node.js服务器,在其中运行我们的项目。在这个服务器中,我们将调用一个名为
upload的 cloudinary 函数来获取所选路径中的图像,并将其上传到我们的 cloudinary 账户中。然后,当我们的URL内的请求是/upload,并使用post方法时,我们将在终端和浏览器中以纯文本形式显示结果。这就是上传文件的元数据。
如下图所示。
//Create a server
http.createServer((req, res) => {
if (req.url === '/upload' && req.method.toLowerCase() === 'post') {
// parse a file upload
const form = new Formidable();
form.parse(req, (err, fields, files) => {
// Find Cloudinary documentation using the link below
// https://cloudinary.com/documentation/upload_images
cloudinary.uploader.upload(files.upload.path, result => {
// This will return the output after the code is exercuted both in the terminal and web browser
// When successful, the output will consist of the metadata of the uploaded file one after the other. These include the name, type, size and many more.
console.log(result)
if (result.public_id) {
// The results in the web browser will be returned inform of plain text formart. We shall use the util that we required at the top of this code to do this.
res.writeHead(200, { 'content-type': 'text/plain' });
res.write('received uploads:\n\n');
res.end(util.inspect({ fields: fields, files: files }));
}
});
});
return;
}
- 现在让我们把我们的程序设置为在运行时返回一个网页。该网页应使用一些CSS、bootstrap和Google字体进行格式化。它将包含一个标题、文件和正文标签中的按钮元素。我们还将把我们的端口号设置为 "5000",这样我们就可以在
localhost:5000。
这里显示了这一点。
// show a file upload form
res.writeHead(200, { 'content-type': 'text/html' });
res.end(`
<!doctype html>
<html lang="en">
<head>
<title>CLOUDINARY UPLOADER</title>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<!-- Custom CSS -->
<style>
@import url('https://fonts.googleapis.com/css2?family=Montserrat:wght@500&display=swap');
* {
font-family: Montserrat;
}
</style>
</head>
<body>
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
<!-- Main Container -->
<div class="container">
<!-- Header -->
<br>
<h1 class="text-center">CLOUDINARY UPLOADER</h1>
<hr>
<p class="text-secondary">This is a simple image uploader system!</p>
<hr>
<!-- Header end.//-->
<!-- Form-->
<form action="/upload" enctype="multipart/form-data" method="post">
<div class="form-group">
<label for="upload-image-file"></label>
<input type="file" class="form-control-file" name="upload" id="upload" placeholder="upload-image-file" aria-describedby="fileHelpId">
<small id="fileHelpId" class="form-text text-muted">Please select the image to be uploaded...</small>
</div>
<button type="submit" class="btn btn-primary" value="Upload">Upload</button>
</form>
<!-- Form end.//-->
</div>
<!--container end.//-->
</body>
</html>
`);
// Port number
}).listen(5000);
配置.env文件
打开".env "文件。在其中,让我们设置我们的Cloudinary名称、API密钥和API秘密。这些都可以在 Cloudinary 仪表板中找到,如下图所示。

**注意:**记住,这些都是重要的凭证,允许人们轻松访问你的Cloudinary账户。确保它们不会暴露在任何地方。不要以任何方式将它们保存在一个在线存储库中。我更建议你添加一个
.gitignore文件,并在其中包含.env文件。始终启用GitGuardian来检查项目中是否有暴露的密钥。
.env 文件的格式将如图所示。
CLOUD_NAME=
API_KEY=
API_SECRET=
直接从你的仪表板上复制并粘贴证书到文件中。保存该文件。
运行代码
现在你可以继续运行代码了。
这可以通过在终端上运行下面的命令来完成。
nodemon run dev
打开一个网页浏览器,在URL中,通过localhost:5000 ,访问网页。
它将看起来像这样。

按 "选择文件 "按钮选择图片,然后点击 "上传 "按钮进行上传。
如果成功,它将显示如下。元数据将根据上传的文件而改变。

打开您的cloudinary网站并登录。在仪表板下,查看上传的图像。你可以使用板上的AI随意操作它。
Cloudinary默认为每个上传的文件(无论是图像还是视频)自动分配一个独特的public_id。
干得好,你已经使用一个简单的Node.js程序成功地将图片上传到你的Cloudinary账户了
总结
我们已经从本教程中获得了以下知识。
- 什么是Cloudinary。
- 支持的语言和框架。
- 如何使用Node.js向Cloudinary上传图片。
- 简要介绍一下什么是
.env文件及其用途。