网页可显示图片但无法获取文件名的技术求助
解决方案:获取服务器目录中的文件列表
前端JavaScript运行在浏览器沙箱中,没有权限直接访问服务器的文件系统,必须通过后端提供接口来实现目录文件的读取,以下是几种常见技术栈的实现方案:
1. Node.js + Express 后端实现
后端代码(server.js)
const express = require('express'); const fs = require('fs'); const path = require('path'); const app = express(); // 处理跨域(前后端域名不同时需要) app.use((req, res, next) => { res.header('Access-Control-Allow-Origin', '*'); res.header('Access-Control-Allow-Methods', 'GET'); next(); }); // 定义获取文件列表的接口 app.get('/api/files', (req, res) => { const targetDir = path.resolve(__dirname, './'); // 指定要读取的目录 fs.readdir(targetDir, (err, files) => { if (err) { return res.status(500).json({ error: '无法读取目录' }); } // 可选:过滤出图片格式的文件 const imageFiles = files.filter(file => /\.(png|jpg|jpeg|gif)$/i.test(file)); res.json(imageFiles); }); }); app.listen(3000, () => { console.log('服务器运行在 http://localhost:3000'); });
前端代码
// 请求后端接口获取文件列表 fetch('http://localhost:3000/api/files') .then(response => response.json()) .then(files => { files.forEach(file => { console.log(file); // 打印目录中的图片文件名 }); }) .catch(err => console.error('请求失败:', err));
2. PHP 后端实现
后端代码(get-files.php)
<?php header('Content-Type: application/json'); header('Access-Control-Allow-Origin: *'); $targetDir = './'; // 指定要读取的目录 $files = scandir($targetDir); if (!$files) { echo json_encode(['error' => '无法读取目录']); exit; } // 过滤掉系统默认的.和..,并筛选图片文件 $imageFiles = array_filter($files, function($file) { return !in_array($file, ['.', '..']) && preg_match('/\.(png|jpg|jpeg|gif)$/i', $file); }); echo json_encode(array_values($imageFiles)); ?>
前端代码
fetch('http://你的服务器地址/get-files.php') .then(response => response.json()) .then(files => { files.forEach(file => console.log(file)); }) .catch(err => console.error('请求失败:', err));
3. Python Flask 后端实现
后端代码(app.py)
from flask import Flask, jsonify import os from flask_cors import CORS app = Flask(__name__) CORS(app) # 处理跨域 @app.route('/api/files', methods=['GET']) def get_files(): target_dir = './' # 指定要读取的目录 try: files = os.listdir(target_dir) # 过滤图片文件并排除隐藏文件 image_files = [f for f in files if f.lower().endswith(('.png', '.jpg', '.jpeg', '.gif')) and not f.startswith('.')] return jsonify(image_files) except Exception as e: return jsonify({'error': str(e)}), 500 if __name__ == '__main__': app.run(host='0.0.0.0', port=5000)
前端代码
fetch('http://localhost:5000/api/files') .then(response => response.json()) .then(files => files.forEach(file => console.log(file))) .catch(err => console.error('请求失败:', err));
重要安全提示
- 严格限制接口可访问的目录,禁止使用用户可控的路径参数,防止目录遍历攻击
- 只返回允许公开访问的文件,过滤掉配置文件、敏感文档等非公开内容
- 可选:添加用户权限校验,确保只有合法用户能调用该接口
内容的提问来源于stack exchange,提问作者got here
相关产品推荐
相关产品推荐

