Node.js 中托管本地图片文件

请先学习
前端小白安装node、vue、Express、Electron及(Electron桌面端exe应用开发)
Electron结合vue3 打包

一、实现操作步骤

(一)、安装 Node.js 和 npm

确保你的系统上已经安装了 Node.js 和 npm。

(二)、创建项目文件夹

创建一个新的文件夹作为你的项目根目录。

(三)、初始化项目

在项目根目录中运行 npm init 来初始化一个新的 Node.js 项目。

(四)、安装 Express

安装 Express.js 框架和相关依赖。

(五)、编写服务器代码

创建一个服务器文件,如 app.js,并配置 Express 来托管本地盘上的图片。

二、具体实操

(一)、新建文件路径

G:\codevue>mkdir nodeimage

(二)、安装 Express

G:\codevue>cd nodeimage
npm install express --save

(三)、nodeimage新建app.js文件

1. 实现代码

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

const app = express();

// 配置托管 C 盘上的图片文件夹
const imageFolderPath = 'G:\\codevue\\images'; // 替换为你的图片文件夹路径

// 创建中间件来处理图片文件的请求
app.use('/images', (req, res) => {
    const decodedPath = decodeURIComponent(req.path.replace('/images', ''));
      // 处理 URL 中的空格
    const urlWithSpacesReplaced = decodedPath.replace('/%20/g', '_'); // 假设文件名中的空格被替换成了下划线
  
    const imagePath = path.join(imageFolderPath, urlWithSpacesReplaced);
//   const imagePath = path.join(imageFolderPath, req.path.replace('/images', ''));

  // 检查文件是否存在
  fs.access(imagePath, fs.constants.F_OK, (err) => {
    if (err) {
      // 文件不存在,返回 404 错误
      res.status(404).send('File not found');
    } else {
      // 文件存在,读取文件并发送到客户端
      fs.readFile(imagePath, (err, data) => {
        if (err) {
          res.status(500).send('Error reading file');
        } else {
          // 设置正确的 MIME 类型
          const mimeType = getMimeType(imagePath);
          res.setHeader('Content-Type', mimeType);
          res.send(data);
        }
      });
    }
  });
});

// 获取文件的 MIME 类型
function getMimeType(filePath) {
  const ext = path.extname(filePath).toLowerCase();
  const mimeTypes = {
    '.jpg': 'image/jpeg',
    '.jpeg': 'image/jpeg',
    '.png': 'image/png',
    '.gif': 'image/gif',
    // 可以添加更多 MIME 类型
  };
  return mimeTypes[ext] || 'application/octet-stream';
}

// 启动服务器
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`);
});

2.情况说明

情况一:图片里面存在中文描述,需要增加解析中文。

const decodedPath = decodeURIComponent(req.path.replace('/images', ''));

情况二:图片里面存在特殊字符_,需要转化

const urlWithSpacesReplaced = decodedPath.replace('/%20/g', '_'); 

(四)、运行服务器

1.启动

# 执行 G:\codevue>cd nodeimage 路径下
node app.js

2.图片访问

本地路径

G:\codevue\images\default - 副本.png

浏览器访问

http://localhost:3000/images/default%20-%20%E5%89%AF%E6%9C%AC.png
  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

金融小白数据分析之路

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值