0%

nodejs部署后端项目教程

nodejs部署后端项目教程(以部署图片压缩接口为例)

这里我们将使用 Node.js 和 Express 框架来构建后端,并使用 sharp 库来进行图片压缩。

首先,确保你已经安装了 Node.js 和 npm。然后,创建一个新的项目目录,并初始化一个新的 Node.js 项目:

mkdir image-compressor-backend
cd image-compressor-backend
npm init -y

接下来,安装所需的依赖项:

npm install express sharp multer

然后,创建一个 server.js 文件,并添加以下代码来构建后端服务:

const express = require('express');
const sharp = require('sharp');
const multer = require('multer');
const path = require('path');
const fs = require('fs');

const app = express();
const port = 3001; // 确保与前端通信的端口不同

// 设置 multer 存储配置
const storage = multer.memoryStorage();
const upload = multer({ storage: storage });

// 处理图片压缩请求
app.post('/compress', upload.single('image'), async (req, res) => {
const file = req.file;
if (!file) {
return res.status(400).send('No file uploaded.');
}

const quality = parseInt(req.body.quality, 10) || 80; // 默认质量为80%
const maxWidth = parseInt(req.body.maxWidth, 10) || 2000;
const maxHeight = parseInt(req.body.maxHeight, 10) || 2000;

try {
// 使用 sharp 进行图片压缩
const compressedBuffer = await sharp(file.buffer)
.resize({ width: maxWidth, height: maxHeight, fit: 'inside', withoutEnlargement: true })
.jpeg({ quality: quality })
.toBuffer();

// 设置响应头并发送压缩后的图片
res.set({
'Content-Type': 'image/jpeg',
'Content-Length': compressedBuffer.length,
});
res.send(compressedBuffer);
} catch (error) {
console.error('Error compressing image:', error);
res.status(500).send('Error compressing image.');
}
});

// 启动服务器
app.listen(port, () => {
console.log(`Server is running at http://localhost:${port}`);
});

这个后端服务监听在端口 3001 上,并提供了一个 /compress 路由来处理图片压缩请求。它使用 multer 中间件来处理文件上传,并使用 sharp 库来进行图片压缩。

前端代码需要稍作修改以与这个后端服务配合。特别是,compressFile 函数需要发送一个请求到后端来压缩图片。这里是一个修改后的 compressFile 函数示例:

import requests
from PIL import Image
import io

# 假设你有一个字典来存储文件名和对应的文件对象
files = {
'example.jpg': open('path/to/example.jpg', 'rb')
}

def compress_file(file_name):
file_data = files.get(file_name)
if not file_data:
return

# 获取质量值(这里假设是从某个地方获取的,比如用户输入)
quality = 80 # 示例值,你可以从UI或其他地方获取这个值

# 设置最大宽度和高度
max_width = 2000
max_height = 2000

# 创建表单数据
form_data = {
'image': file_data,
'quality': quality,
'maxWidth': max_width,
'maxHeight': max_height
}

try:
# 发送POST请求
response = requests.post('http://localhost:3001/compress', files=form_data)

# 检查响应状态码
if response.status_code != 200:
response.raise_for_status()

# 获取压缩后的图像数据
compressed_image_data = response.content

# 将图像数据保存为文件
compressed_file_name = 'compressed-' + file_name
with open(compressed_file_name, 'wb') as compressed_file:
compressed_file.write(compressed_image_data)

# 更新文件字典(如果需要)
files[file_name] = {
'original': file_data,
'compressed': open(compressed_file_name, 'rb')
}

# 更新文件列表(这个函数需要你根据实际需求实现)
update_file_list()

except requests.RequestException as e:
print(f"压缩 {file_name} 失败: {e}")

# 示例调用
compress_file('example.jpg')

# 注意:这个函数需要在适当的地方被调用,并且需要确保文件路径和服务器地址是正确的。

请注意,这个示例假设前端和后端运行在同一个域下,或者你已经配置了 CORS(跨源资源共享)来允许前端与后端通信。如果你遇到跨域问题,你可能需要在后端添加适当的 CORS 头。

现在,当你运行后端服务器并使用前端页面上传和压缩图片时,前端会将图片发送到后端的 /compress 路由,后端会使用 sharp 库进行压缩,并将压缩后的图片发送回前端。前端然后会显示压缩后的图片,并提供下载选项。