Created
February 27, 2025 02:06
-
-
Save noahjames404/d85f4cac0292b2632839184aa4571c7c to your computer and use it in GitHub Desktop.
Strapi Upload Plugin Middleware, change format of avif file to webp to support multiple file formats
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * `upload-plugin` middleware | |
| */ | |
| import * as fs from 'fs'; | |
| import type { Core } from '@strapi/strapi'; | |
| import sharp from 'sharp'; | |
| import formidable, { PersistentFile } from 'formidable'; | |
| import path from 'path'; | |
| import { Context } from 'koa' | |
| export default (config, { strapi }: { strapi: Core.Strapi }) => { | |
| return async (ctx: Context, next) => { | |
| if (ctx.request.path === '/api/upload' && ctx.request.method === 'POST') { | |
| // Example: Rename files before they are processed | |
| // console.log("Array.isArray(ctx.request.files) ", Array.isArray(ctx.request.files)); | |
| const files: formidable.File[] = Array.isArray(ctx.request.files.files) ? ctx.request.files.files : [ctx.request.files.files]; | |
| try { | |
| //Prevent having unlink or busy errors on windows platform. | |
| sharp.cache({ files: 0 }); | |
| console.log("files length", files.length); | |
| var files_formatted = await Promise.all(files.map(async e => { | |
| // console.log(e.filepath, e); | |
| // console.log("logged",e); | |
| if (e.mimetype != "image/avif") return e; | |
| var newFilePath = e.filepath; | |
| var data = fs.readFileSync(e.filepath); | |
| //generate file and post it on new file path | |
| await sharp(data) | |
| .toFormat("webp") | |
| .toFile(newFilePath); | |
| var converted = fs.readFileSync(newFilePath); | |
| const formFile: formidable.File = { | |
| size: converted.length, | |
| originalFilename: path.basename(e.originalFilename), | |
| filepath: newFilePath, | |
| newFilename: path.basename(newFilePath), | |
| hashAlgorithm: null, | |
| mimetype: "image/webp", | |
| toJSON: null | |
| }; | |
| var pf = new PersistentFile(formFile); | |
| // console.log("Persitent!!!",pf); | |
| return pf; | |
| return formFile; | |
| })); | |
| ctx.request.files.files = null | |
| //@ts-ignore | |
| ctx.request.files.files = files_formatted; | |
| console.log("var data", ctx.request.files); | |
| } catch (err) { | |
| console.error(err); | |
| } | |
| } | |
| strapi.log.info('In upload-plugin middleware.'); | |
| await next(); | |
| }; | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment