Hello, i am trying to upload a file from the tmp folder to my Bookmark model using upload plugin
but i cant make it work because i am doing it wrong and know how to make it work
i have the following bookmark collection field
basically what i am trying to achieve is, i take the URL field take screenshot of the page then save it to the tmp folder and then upload file from the tmp to the THUMB field using the upload plugin
can some masters help me pls.
this is the code
models/bookmark.js
"use strict";
const captureWebsite = require("capture-website");
const blurhash = require("blurhash");
const _ = require("lodash");
const sharp = require("sharp");
const options = {
width: 1680,
height: 1260,
launchOptions: {
args: ["--no-sandbox", "--disable-web-security"],
},
};
module.exports = {
lifecycles: {
// Called before an entry is created
async beforeCreate(bookmark) {
const file = `/tmp/${bookmark.slug}.jpg`;
if (bookmark.url) {
try {
// capture screenshot
await captureWebsite.file(bookmark.url, file, options);
const buffer = await captureWebsite.buffer(bookmark.url, options);
const screenshotData = {
name: `${bookmark.slug}.jpg`,
hash: `${bookmark.slug}`,
path: undefined,
ext: ".jpg",
mime: "image/jpg",
buffer,
};
// console.log("screenshotData", screenshotData);
// Image manipulation process (same as upload plugin)
const {
getDimensions,
generateThumbnail,
generateResponsiveFormats,
} = strapi.plugins.upload.services["image-manipulation"];
const thumbnailFile = await generateThumbnail(screenshotData);
// Generate blurhash
const encodeImageToBlurhash = (imageBuffer) =>
new Promise((resolve, reject) => {
sharp(imageBuffer)
.raw()
.ensureAlpha()
.toBuffer((err, buffer, { width, height }) => {
if (err) return reject(err);
resolve(
blurhash.encode(
new Uint8ClampedArray(buffer),
width,
height,
4,
4
)
);
});
});
const blurHash = await encodeImageToBlurhash(thumbnailFile.buffer);
bookmark.blurHash = blurHash;
await strapi.plugins.upload.provider.upload(thumbnailFile);
delete thumbnailFile.buffer;
_.set(bookmark.thumb, "formats.thumbnail", thumbnailFile);
const formats = await generateResponsiveFormats(screenshotData);
if (Array.isArray(formats) && formats.length > 0) {
for (const format of formats) {
if (!format) continue;
const { key, file } = format;
await strapi.plugins.upload.provider.upload(file);
delete file.buffer;
_.set(bookmark.thumb, ["formats", key], file);
}
}
console.log(bookmark);
} catch (e) {
console.log("eerroorr", e);
}
}
},
},
};
all i get is
{
title: 'Strapi',
slug: 'strapi',
url: 'https://strapi.io/',
created_by: 1,
updated_by: 1,
blurHash: 'UMI5T7ND00%L00M^~pIV?a%3WBt3?ZIWD*j='
}