Skip to content

Instantly share code, notes, and snippets.

@SoftCreatR
Last active November 10, 2023 13:10
Show Gist options
  • Save SoftCreatR/379479631d3fe569c99282916e07c0bc to your computer and use it in GitHub Desktop.
Save SoftCreatR/379479631d3fe569c99282916e07c0bc to your computer and use it in GitHub Desktop.
Strapi 4 Blurhash
// ./src/extensions/blurhash.js
const plaiceholder = require('plaiceholder')
const _ = require('lodash')
module.exports = {
generatePlaceholder (strapi) {
strapi.contentType('plugin::upload.file').attributes.placeholder = {
type: 'text'
}
strapi.plugin('upload').services.upload.uploadFileAndPersist = async function (fileData, { user } = {}) {
const config = strapi.config.get('plugin.upload')
const {
getDimensions,
generateThumbnail,
generateResponsiveFormats,
isSupportedImage
} = strapi.plugin('upload').service('image-manipulation')
await strapi.plugin('upload').service('provider').upload(fileData)
if (await isSupportedImage(fileData)) {
const thumbnailFile = await generateThumbnail(fileData)
if (thumbnailFile) {
await strapi.plugin('upload').service('provider').upload(thumbnailFile)
try {
await plaiceholder
.getPlaiceholder(thumbnailFile.url)
.then(({ base64 }) => { fileData.placeholder = base64 })
} catch (e) {
fileData.placeholder = ''
}
delete thumbnailFile.buffer
_.set(fileData, 'formats.thumbnail', thumbnailFile)
}
const formats = await generateResponsiveFormats(fileData)
if (Array.isArray(formats) && formats.length > 0) {
for (const format of formats) {
if (!format) { continue }
const { key, file } = format
strapi.plugin('upload').service('provider').upload(file)
_.set(fileData, ['formats', key], file)
}
}
const { width, height } = await getDimensions(fileData)
_.assign(fileData, {
provider: config.provider,
width,
height
})
}
return this.add(fileData, { user })
}
}
}
// ./src/index.js
const blurhash = require('./extensions/blurhash');
register({ strapi }) {
blurhash.generatePlaceholder(strapi);
},
@ksparsh2011
Copy link

Hi, I'm migrating my strapi v3 to v4, are there any changes in plugins.ts file as well? considering upload is now a core feature of strapi but not a plugin anymore? are there any other changes that you might have faced related to Mt media library?

@SoftCreatR
Copy link
Author

This Plugin was written for Strapi v4 anyways. So the code here should be all you need. However, I'm no longer using Strapi, but I'm sure, that there are alternatives to this here already.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment