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 小时前
🎉 开源项目推荐 | 让你的 TypeScript/React 项目瘦身更简单!
node.js·前端工程化
醉书生ꦿ℘゜এ1 小时前
npm error Cannot read properties of null (reading ‘matches‘)
前端·npm·node.js
超级土豆粉2 小时前
从0到1写一个适用于Node.js的User Agent生成库
linux·ubuntu·node.js
空中湖5 小时前
‘pnpm‘ 不是内部或外部命令,也不是可运行的程序
npm·node.js
SailingCoder6 小时前
grafana-mcp-analyzer:基于 MCP 的轻量 AI 分析监控图表的运维神器!
运维·人工智能·typescript·node.js·grafana
又又呢9 小时前
前端面试题总结——webpack篇
前端·webpack·node.js
avoidaily16 小时前
使用Node.js分片上传大文件到阿里云OSS
阿里云·node.js·云计算
xd0000216 小时前
8.axios Http网络请求库(1)
node.js
孟孟~17 小时前
npm run dev 报错:Error: error:0308010C:digital envelope routines::unsupported
前端·npm·node.js
孟孟~17 小时前
npm install 报错:npm error: ...node_modules\deasync npm error command failed
前端·npm·node.js