当前位置:   article > 正文

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

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
  • 1

(二)、安装 Express

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

(三)、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}`);
});
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57

2.情况说明

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

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

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

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

(四)、运行服务器

1.启动

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

2.图片访问

本地路径

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

浏览器访问

http://localhost:3000/images/default%20-%20%E5%89%AF%E6%9C%AC.png
  • 1
声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号