Node.js 是一个基于 Chrome V8 引擎的 JavaScript 运行时环境,具有高效、轻量级和事件驱动的特性。在 Node.js 中,可以使用各种模块和库来实现图片上传功能。
在本文中,我们将介绍如何使用 Node.js 来实现图片上传功能。以下是一个简单的示例代码:
const http = require('http');
const formidable = require('formidable');
const fs = require('fs');
const server = http.createServer((req, res) => {
if (req.url === '/upload' && req.method.toLowerCase() === 'post') {
const form = new formidable.IncomingForm();
form.parse(req, (err, fields, files) => {
if (err) {
console.error(err);
res.writeHead(500, { 'Content-Type': 'text/plain' });
res.end('Internal Server Error');
return;
}
const oldPath = files.file.path;
const newPath = './uploads/' + files.file.name;
fs.rename(oldPath, newPath, (err) => {
if (err) {
console.error(err);
res.writeHead(500, { 'Content-Type': 'text/plain' });
res.end('Internal Server Error');
return;
}
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('File uploaded');
});
});
} else {
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('Not Found');
}
});
server.listen(3000, () => {
console.log('Server started on port 3000');
});
上述代码使用了 http
、formidable
和 fs
模块,其中:
http
模块用于创建 HTTP 服务器,接收客户端请求。formidable
模块用于解析客户端提交的表单数据,包括上传的文件。fs
模块用于操作文件系统,包括移动上传的文件到指定目录。
代码中,我们创建了一个 HTTP 服务器,监听 3000 端口。当客户端发送一个以 /upload
结尾的 POST 请求时,我们使用 formidable
模块解析请求中的数据。解析完成后,我们将上传的文件移动到 ./uploads/
目录下,并向客户端返回上传成功的消息。
使用上述示例代码,你需要先安装 formidable
模块,可以通过以下命令来安装:
$ npm install formidable
同时,你需要在项目根目录下创建一个 uploads
文件夹,用于存储上传的图片。
完成以上准备工作后,你可以运行代码,并使用 POST 请求向服务器发送图片数据,例如使用 cURL 命令:
$ curl -X POST -F "file=@/path/to/image.jpg" http://localhost:3000/upload
在实际应用中,你可以根据需求进一步对上传的图片进行处理,例如缩放、裁剪等操作。