Next 14 Server Actions中如何获取FormData的图片Buffer?
如何在Next.js 14 Server Actions中获取上传图片的Buffer
问题背景
我正在使用Next 14结合Server Actions开发表单,并集成了富文本编辑器ReactQuill。目前已能在服务端获取表单值,但不知道如何获取上传图片的Buffer来进行处理。
客户端简化表单代码
"use client" export default function NewCompositionForm() { const [content, setContent] = useState(""); const createCompositionAction = actions.createComposition.bind(null, content); return ( <form className="bg-bgCustom pt-4 h-screen rounded-md px-2" action={createCompositionAction} > ... <div className="flex"> <label htmlFor="edition" className="w-1/6 text-xl"> Imágenes </label> <input type="file" id="images" name="images" className="w-5/6 rounded-md px-2 py-1 text-xl" placeholder="Introduce Editor" multiple /> </div> <div className="flex flex-col"> <label htmlFor="ext_media" className="text-xl mb-4"> Descripción y/o anotaciones </label> <ReactQuill value={content} onChange={setContent} theme="snow" id="description" name="description" className=" bg-slate-50" modules={quillModules} formats={quillFormats} placeholder="Escribe aquí toda la información de la obra." /> </div> <button type="submit">Agregar</button> </form>
服务端代码
"use server" export async function createComposition(content, formData) { console.log("Content: ", content) console.log("FormData: ", formData) console.log(formData.getAll('images')) }
终端输出
Content: <p><a href="DUDE" rel="noopener noreferrer" target="_blank"><strong>DUDE</strong></a></p> FormData: FormData { [Symbol(state)]: [ { name: 'type', value: 'camara' }, { name: 'title', value: 'TITULO!!!' }, { name: 'rev', value: '' }, { name: 'length', value: '' }, { name: 'edition', value: '' }, { name: 'images', value: [File] }, { name: 'images', value: [File] } ] } File { size: 13397612, type: 'image/png', name: 'Porsche 911 Blue Render.png', lastModified: 1706694592197 }
请问如何从这里处理这些多文件,获取图片的Buffer值?
解决方案
服务端拿到的File对象遵循Web File API规范,可通过以下步骤转换为Node.js的Buffer:
- 调用文件对象的
arrayBuffer()方法获取ArrayBuffer(异步操作) - 使用
Buffer.from()将ArrayBuffer转换为Node.js Buffer - 用
Promise.all()批量处理多个文件的异步转换
修改后的服务端代码示例:
"use server" export async function createComposition(content, formData) { // 获取所有上传的图片文件 const imageFiles = formData.getAll('images'); // 批量转换为Buffer const imageBuffers = await Promise.all( imageFiles.map(async (file) => { // 先获取ArrayBuffer const arrayBuffer = await file.arrayBuffer(); // 转换为Node.js Buffer return Buffer.from(arrayBuffer); }) ); // 此时imageBuffers就是所有图片的Buffer数组,可用于后续存储或处理 console.log('图片Buffer列表:', imageBuffers); console.log('第一张图片的Buffer长度:', imageBuffers[0]?.length); // 同时可以保留文件元信息,比如文件名、类型 const imageDetails = imageFiles.map((file, index) => ({ name: file.name, type: file.type, size: file.size, buffer: imageBuffers[index] })); console.log('图片详情(含Buffer):', imageDetails); // 其他业务逻辑... }
关键说明
arrayBuffer()是异步方法,必须用await等待结果,多个文件时用Promise.all确保所有转换完成- Node.js环境下
Buffer.from(arrayBuffer)是直接转换的,无需额外依赖 - 文件的元数据(文件名、类型、大小)可以直接从原始
File对象上读取,搭配Buffer一起使用更方便
内容的提问来源于stack exchange,提问作者AlZ
相关产品推荐
相关产品推荐

