You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在HTML和ExpressJS中实现文件输入框多选文件?

解决文件输入框多选及目录选择问题

前端实现多选文件

要让文件输入框支持多选,只需给<input type="file">添加multiple属性,修改后的代码如下:

<div id="input-div-2">
  <input id="program-input" required type="file" multiple name="file input">
</div>

添加该属性后,用户可通过按住Ctrl(Windows)或Command(Mac)键选择多个文件,也可直接框选批量文件。

关于设置value="/6/"无效的原因

浏览器出于安全限制,不允许通过代码直接设置文件输入框的value属性来指定本地文件/目录路径,必须由用户手动选择文件,防止网页未经授权访问本地文件系统。

选择整个文件夹的方案

如果需要支持选择整个文件夹(包含子目录文件),可以使用directory标准属性(现代浏览器支持),配合兼容旧版Chrome的webkitdirectory属性,代码如下:

<div id="input-div-2">
  <input id="program-input" required type="file" directory webkitdirectory name="file input">
</div>

用户选择文件夹后,输入框会自动包含该文件夹下的所有文件(包括子目录中的文件)。

Node.js文件系统解决方案

1. 处理前端上传的多文件(Express + Multer)

如果需要在后端接收前端上传的多文件,可以用Express框架配合multer中间件实现:

安装依赖

npm install express multer

后端代码示例

const express = require('express');
const multer = require('multer');
const app = express();
const port = 3000;

// 配置文件存储路径与命名规则
const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, './uploads/'); // 需提前创建uploads目录
  },
  filename: (req, file, cb) => {
    cb(null, `${Date.now()}-${file.originalname}`); // 避免文件名重复
  }
});

const upload = multer({ storage: storage });

// 处理多文件上传的接口,支持最多10个文件
app.post('/upload', upload.array('file input', 10), (req, res) => {
  console.log('已上传文件列表:', req.files);
  res.status(200).send('文件上传完成');
});

app.listen(port, () => {
  console.log(`服务器运行在 http://localhost:${port}`);
});

2. 后端读取指定目录下的文件(fs模块)

如果需要在后端遍历本地目录(比如读取/6/目录下的所有文件),可以使用Node.js内置的fs模块:

const fs = require('fs').promises;
const path = require('path');

async function scanDirectory(dirPath) {
  try {
    const entries = await fs.readdir(dirPath, { withFileTypes: true });
    const filePaths = [];
    for (const entry of entries) {
      const fullPath = path.join(dirPath, entry.name);
      if (entry.isDirectory()) {
        // 递归扫描子目录
        const subFiles = await scanDirectory(fullPath);
        filePaths.push(...subFiles);
      } else {
        filePaths.push(fullPath);
      }
    }
    return filePaths;
  } catch (error) {
    console.error('扫描目录失败:', error);
  }
}

// 调用示例:扫描./6/目录
scanDirectory('./6/').then(files => console.log('目录文件列表:', files));

内容的提问来源于stack exchange,提问作者cihan toker

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 09:52:33