Express使用Formidable上传时将多文件名字符串转为数组的方法
问题描述
我有一个存储多文件名的字符串变量filename,需要将所有文件名提取后存入数组,多次尝试都未得到预期结果。
测试代码:console.log(filename);
输出的字符串内容:
4ca9da0b-177b-4e8b-ab10-a9633720c1c8getg3434yy.jpg c721af11-5e6a-43ce-8acc-c9ab86c94c6fhe45yu45uy54y45uj4ju.jpg 3f8e602c-aa64-4c8f-ac5e-ad824bfbfc34h34yh3hyjk5 456j.png fb05e659-be7a-4f81-8f16-5fb270121b3brjk5ryjkj64iju6i.jpg
预期的数组格式:
[ "a950e85b-7cec-487d-9186-38d131d83772g34ygh3435hyu4uu.jpg", "4ca9da0b-177b-4e8b-ab10-a9633720c1c8getg3434yy.jpg", "c721af11-5e6a-43ce-8acc-c9ab86c94c6fhe45yu45uy54y45uj4ju.jpg", "3f8e602c-aa64-4c8f-ac5e-ad824bfbfc34h34yh3hyjk5 456j.png", "fb05e659-be7a-4f81-8f16-5fb270121b3brjk5ryjkj64iju6i.jpg" ]
我最初的实现代码:
let array = []; for (let index = 0; index <= filename.length; index++) { const element = filename[index]; array.push(element); } console.log(array);
这段代码运行后会将文件名拆分为单个字符存入数组,同时出现undefined值,错误输出示例:
[ 'c56f6f49-197c-46a4-8f33-eb92c7486410g34ygh3435hyu4uu.jpg','c','5','6','f','6','f','4','9','-','1','9','7','c','-','4','6','a','4','-','8','f','3','3','-','e','b','9','2','c','7','4','8','6','4','1','0','g','3','4','y','g','h','3','4','3','5','h','y','u','4','u','u','.','j','p','g', undefined ]
完整代码补充
import { Request, Response } from "express"; import { File } from "formidable"; import Formidable from "formidable-serverless"; import fs from "fs"; import { v4 as uuidv4 } from "uuid"; export const config = { api: { bodyParser: false, }, }; export default function uploadFormFiles(req: Request, res: Response) { return new Promise(async (resolve, reject) => { const form = new Formidable.IncomingForm({ multiples: true, keepExtensions: true, }); form .on("file", (name: string, file: File) => { const filename = uuidv4() + file.name; let array = []; for (let index = 0; index <= filename.length; index++) { const element = filename[index]; array.push(element); } console.log(array); const data = fs.readFileSync(file.path); fs.writeFileSync(`public/upload/${filename}`, data); fs.unlinkSync(file.path); }) .on("aborted", () => { reject(res.status(500).send("Aborted")); }) .on("end", () => { resolve(res.status(200).send("done")); }); await form.parse(req); }); }
问题原因
- 循环条件错误:
index <= filename.length会导致索引超出字符串最大范围,最后一次取值为undefined,这就是报错中undefined的来源 - 遍历逻辑错误:
filename本身是单个文件名的字符串,直接遍历字符串索引得到的是单个字符,所以会出现拆分文件名的问题 - 数组作用域错误:数组声明在
file事件回调内部,每次触发文件事件都会新建空数组,无法把所有文件名收集到同一个数组中
解决方案
如果要通过监听file事件收集所有文件名,将数组声明移到事件回调外部即可:
export default function uploadFormFiles(req: Request, res: Response) { return new Promise(async (resolve, reject) => { const form = new Formidable.IncomingForm({ multiples: true, keepExtensions: true, }); // 数组声明在回调外部 const filenameArray = []; form .on("file", (name: string, file: File) => { const filename = uuidv4() + file.name; // 直接存入整个文件名,不需要遍历字符串 filenameArray.push(filename); const data = fs.readFileSync(file.path); fs.writeFileSync(`public/upload/${filename}`, data); fs.unlinkSync(file.path); }) .on("aborted", () => { reject(res.status(500).send("Aborted")); }) .on("end", () => { // 所有文件处理完成后即可拿到完整的文件名数组 console.log(filenameArray); resolve(res.status(200).send("done")); }); await form.parse(req); }); }
你后续补充的实现方案更简洁,直接在parse回调中对文件数组做map处理,一次性生成所有带uuid前缀的文件名:
const fields = new Formidable.IncomingForm({ multiples: true, keepExtensions: false, }); fields.parse(req, (err, fields, files) => { let filenameArray = files.file.map((a) => uuidv4() + a.name); // 后续业务逻辑 })
内容的提问来源于stack exchange,提问作者Aland Sleman
相关产品推荐
相关产品推荐

