浏览器端JavaScript如何单次请求获取目录下所有文件为Blob?
问题
我现在通过以下代码从应用的public文件夹获取单个文件:
import Pdf from "../assets/sample/Sample.pdf"; const response = await axios({ method: "post", url: Pdf, responseType: "blob", });
我想一次性获取sample目录下的所有文件,而不是像现在这样多次请求(当前多请求实现代码如下),想知道请求目录时responseType该设成什么?
const getFilesFromFolder = async () => { const response = await axios.all([ makeRequestForSingleFile(Pdf), makeRequestForSingleFile("/src/assets/sample/Sample.docx"), makeRequestForSingleFile("/src/assets/sample/Sample.ppt"), ]); return response.map(obj => obj.data); };
解决方案
首先明确:前端直接请求静态资源目录,默认拿不到目录下的文件列表——因为静态资源服务器(比如Nginx、Express默认配置)不会主动返回目录内容,得先解决这个核心问题,再谈responseType的设置。
方案1:配置服务器返回目录列表
如果你的项目有后端服务(比如Express),可以给静态资源目录开启目录列表功能,此时请求目录URL会返回HTML格式的文件列表,responseType设为'text',之后解析HTML提取文件名再批量请求文件。
举个Express的配置例子:
const express = require('express'); const serveIndex = require('serve-index'); const app = express(); // 配置静态资源访问+目录列表 app.use('/assets', express.static('public/assets'), serveIndex('public/assets', {'icons': true}));
前端对应的请求代码:
const getFolderFiles = async () => { // 请求sample目录,获取HTML格式的文件列表 const dirRes = await axios({ method: 'get', url: '/assets/sample/', responseType: 'text' }); // 从HTML里提取目标格式的文件名(这里用正则简单处理,复杂场景可以用DOMParser解析) const fileNames = dirRes.data.match(/href="([^"]+\.(pdf|docx|ppt))"/g)?.map(item => { return item.replace('href="', '').replace('"', ''); }) || []; // 批量请求所有文件 const fileResponses = await axios.all(fileNames.map(file => { return axios({ method: 'get', url: `/assets/sample/${file}`, responseType: 'blob' }); })); return fileResponses.map(res => res.data); };
这种情况下,请求目录的responseType是'text',因为服务器返回的是HTML文本。如果服务器配置成返回JSON格式的文件列表,那responseType就设为'json'。
方案2:前端预定义文件清单(无需改服务器)
如果不想折腾服务器配置,最直接的方式就是在前端维护一个sample目录的文件清单,然后批量请求,比你现在的写法更易维护:
// 提前维护sample目录的文件路径清单 const sampleFileList = [ '../assets/sample/Sample.pdf', '../assets/sample/Sample.docx', '../assets/sample/Sample.ppt' ]; const getFilesFromFolder = async () => { const responses = await axios.all(sampleFileList.map(filePath => { return axios({ method: 'get', url: filePath, responseType: 'blob' }); })); return responses.map(res => res.data); };
方案3:打包时自动生成文件清单(适用于Vue/React等项目)
如果是用Webpack、Vite这类构建工具,可以借助插件在打包时自动扫描sample目录,生成文件清单文件,前端导入这个清单再批量请求。比如Vite可以用vite-plugin-list-files插件,Webpack可以自定义插件实现这个功能。
内容的提问来源于stack exchange,提问作者hafiz ali
相关产品推荐
相关产品推荐

