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 来托管本地盘上的图片。

二、具体实操

(一)、新建文件路径

bash 复制代码
G:\codevue>mkdir nodeimage

(二)、安装 Express

bash 复制代码
G:\codevue>cd nodeimage
npm install express --save

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

1. 实现代码

js 复制代码
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.情况说明

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

js 复制代码
const decodedPath = decodeURIComponent(req.path.replace('/images', ''));

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

js 复制代码
const urlWithSpacesReplaced = decodedPath.replace('/%20/g', '_'); 

(四)、运行服务器

1.启动

cmd 复制代码
# 执行 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
相关推荐
烟雨空灵1 天前
25 天做了个独立开发者作品橱窗,收录 340+ 件作品,代码全开源
前端·node.js
用户216076340831 天前
1200 个任务里,97 个还开着,0 个我能做
node.js
不要试图纠正别人2 天前
1055 个文件,共享 0 字节:pnpm 硬链接的静默降级
前端·node.js
吴名氏.2 天前
从零手写一个 AI Agent 框架(TypeScript 完整实现):Function Calling 循环、流式输出与错误恢复
人工智能·typescript·node.js·大模型·ai agent·functioncalling·llm 应用开发
关键词安全4 天前
PHP / Node.js / Go / Rust 全部中招(CVE-2026-109618、109619、111497、111943)完整排查与修复清单
golang·rust·node.js
zhensherlock4 天前
Protocol Launcher 系列:CodeHub 移动端 GitHub 协作利器
前端·javascript·typescript·node.js·自动化·github·js
jaysee-sjc5 天前
【黑马点评】Day02:优惠券秒杀与分布式锁
java·分布式·nginx·spring·node.js·tomcat·maven
ZhengEnCi6 天前
Express 企业级项目结构怎么组织:五层骨架、单向依赖和一份能跑的边界检查脚本
javascript·node.js·express
Dumbness6 天前
搜 platform 却给出 Form 表单:离线文档检索把短关键词当成了子串
javascript·node.js
用户216076340837 天前
一个 2 MB 的 .zst 文件,解压出来只有十几 KB
node.js