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

NodeJS中JPEG格式File对象转WebP格式File对象实现方案

将WebP流转换为符合要求的File对象(image/webp)

实现方案

你已经完成JPEG转WebP流的步骤,接下来只需把WebP流写入临时文件,再构造出和示例一致的File对象即可,具体操作如下:

1. 将WebP流写入临时文件

先把转换后的WebP可读流写入系统临时目录,确保流处理完成:

const fs = require('fs');
const { pipeline } = require('stream');
const { promisify } = require('util');
const pipelineAsync = promisify(pipeline);
const os = require('os');
const path = require('path');

// webpStream 是你转换后的WebP格式可读流
const tempFileName = `upload_${Date.now()}.webp`;
const tempFilePath = path.join(os.tmpdir(), tempFileName);

// 用pipeline处理流,确保写入完成
await pipelineAsync(webpStream, fs.createWriteStream(tempFilePath));

2. 构造标准File对象

从示例的File结构来看,你大概率用的是formidable库,直接用它的File类实例化最匹配:

const { File } = require('formidable');

const webpFile = new File({
  path: tempFilePath,
  name: tempFileName, // 也可以替换成原文件名改后缀,比如原name是xxx.jpg就改成xxx.webp
  type: 'image/webp',
  lastModifiedDate: new Date(),
});

// 同步文件大小,formidable的File会自动处理,也可以手动获取
webpFile.size = fs.statSync(tempFilePath).size;
webpFile.hash = null; // 和示例保持一致

如果不用formidable,也可以手动给ReadStream补全File属性:

const webpFile = fs.createReadStream(tempFilePath);

// 补充示例里的所有属性
webpFile.size = fs.statSync(tempFilePath).size;
webpFile.name = tempFileName;
webpFile.type = 'image/webp';
webpFile.hash = null;
webpFile.lastModifiedDate = new Date();
webpFile._writeStream = {
  path: tempFilePath,
  bytesWritten: webpFile.size,
  closed: true,
  // 其他可选属性可根据示例按需补充
};

3. 清理临时文件(重要)

处理完File对象的业务逻辑后,记得删除临时文件释放磁盘空间:

fs.unlinkSync(tempFilePath);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 21:05:11