Strapi: Problem uploading images to strapi, image does not render - javascript

Problem
I would like to know if you can help identify the issue related to uploading an image to the thumb field belonging to the content-type Directory.
The image image does not render once it is in the strapi panel, it only shows the name.
const getFileSize = (filePath) => {
return statSync(filePath)["size"]; // statSync from `fs-extra` library
};
strapi.service("api::directory.directory").create({
data: {},
files: {
thumb: {
path: `${imagesDir}/Crab-1-1-scaled.jpg`,
name: "Crab-1-1-scaled.jpeg",
type: mime.lookup(`${imagesDir}/Crab-1-1-scaled.jpg`), // mime from `mime-types` library
size: getFileSize(`${imagesDir}/Crab-1-1-scaled.jpg`),
},
},
});
console.log
size is always zero
{
files: {
thumb: {
path: 'src/scripts/Directory/images/Crab-1-1-scaled.jpg',
name: 'Crab-1-1-scaled.jpeg',
type: 'image/jpeg',
size: 0
}
}
}
output
When uploading the data the image is not rendered, it only shows the name of the image.

Related

LwcWebpackPlugin with AliasModuleRecord for lwc.dev isn't loading HTML file for component

I use LwcWebpackPlugin to load Lightning Web Components. Everything works fine but because I want to load compoennts from 'lwc' direcotry the namescape won't work. I must get components from /lwc directory and I bypysed this with AliasModuleRecord (described here) where I import all components by name. Problem is that only JS file is loading. Browser don't throw any exception but HTML body is not rendered. I know that JS file works because console log from connectedCallback is showed in browser console. What I'm doing wrong?. Maybe I haven't imported some library? Here is fragment form my webpack.config.js:
new LwcWebpackPlugin({
modules: [
{ dir: 'src/modules' },
{ npm: 'lightning-base-components' },
...glob.sync(
`./{${sfdxProjectJSON.packageDirectories?.map(package => package.path).join(',')}}/main/default/lwc/**/*.js`,
{ ignore: ['./**/__tests__/**'] }
).map(path => {
const name = path.split('/').at(-2);
return {
"name": `c/${name}`,
"path": path.replace('./', '')
};
}, {})
]
})
and this all resoults with:
[{
name: 'ui/helloWorldExampleOne',
path: 'pb-base/main/default/lwc/helloWorld/__docs__/examples/helloWorldExampleOne/helloWorldExampleOne.js'
},
{
name: 'ui/helloWorld',
path: 'pb-base/main/default/lwc/helloWorld/helloWorld.js'
},
{
name: 'ui/exampleOne',
path: 'pb-commerce/main/default/lwc/exampleOne/exampleOne.js'
}]

output images corrupt when using mdx-bundler + remark-mdx-images

I am writing a site using the remix JavaScript framework.
It is a blog that uses MDX for the blog content. I want to include images within this content.
Background
I am using a combination of mdx-bundler to convert the MDX files into bundles, and the remark-mdx-images plugin to convert the markdown-style image references into image tags.
The Problem:
mdx-bundler is correctly building my Markdown, and is outputting the Image assets into the expected directory. However, the output images appear to be corrupt. I cannot open them in macos Finder. In-browser, requests for these images returns a 200, but the image is not visible.
Here is an example MDX file:
---
slug: hello-world
title: Hello, world
---
testing images
![](./hello-world.png 'Hello World')
Below is the relevant portion of remix config where these two things are used:
const { code, frontmatter } = await bundleMDX({
source: indexFile.content,
files: filesObject,
mdxOptions: options => ({
remarkPlugins: [
...(options.remarkPlugins ?? []),
remarkMdxImages,
remarkSlug,
remarkGfm,
],
rehypePlugins: [
...(options.rehypePlugins ?? []),
[rehypeAutolinkHeadings, { behavior: 'wrap' }],
[rehypePrettyCode, rehypePrettyCodeOptions],
],
}),
esbuildOptions: options => {
options.loader = {
...options.loader,
'.gif': 'file',
'.jpeg': 'file',
'.jpg': 'file',
'.png': 'file',
'.svg': 'file',
'.webp': 'file',
}
// Set write to true so that esbuild will output the files.
options.write = true
options.outdir = path.resolve(`public/build/_assets/${rootDir}/img`)
options.publicPath = path.resolve(`/build/_assets/${rootDir}/img`)
return options
},
})
I'm not entirely sure how to go about debugging this as I am new to MDX, mdx-bundler and remark-mdx-images. All of the output files and locations appear to be correct, it's just the image assets themselves that are corrupted.

Deleting images in Imgbb via API

i'm using the imgbb API since it is very straghtforward to use and quite cheap. The problem is that the documentation is very poor and it does not explain how to delete an image through the API. I want to be able to delete the photo from my server in the case something happens (ex. if I delete a user).
My server is written in node.js.
pd. Also the response object I get after uploading an image is this one:
{
data: {
id: 'c3VRs4x',
title: 'client1-Bali',
url_viewer: 'https://ibb.co/c3VRs4x',
url: 'https://i.ibb.co/Pj0JVqt/client1-Bali.jpg',
display_url: 'https://i.ibb.co/1QjB4Fb/client1-Bali.jpg',
size: 60385,
time: '1594835546',
expiration: '0',
image: {
filename: 'client1-Bali.jpg',
name: 'client1-Bali',
mime: 'image/jpeg',
extension: 'jpg',
url: 'https://i.ibb.co/Pj0JVqt/client1-Bali.jpg'
},
thumb: {
filename: 'client1-Bali.jpg',
name: 'client1-Bali',
mime: 'image/jpeg',
extension: 'jpg',
url: 'https://i.ibb.co/c3VRs4x/client1-Bali.jpg'
},
medium: {
filename: 'client1-Bali.jpg',
name: 'client1-Bali',
mime: 'image/jpeg',
extension: 'jpg',
url: 'https://i.ibb.co/1QjB4Fb/client1-Bali.jpg'
},
delete_url: 'https://ibb.co/c3VRs4x/b3072de2f5287a39f81c7dec3cd8a236'
},
success: true,
status: 200
}
Edit: Here is the link to the imgbb API documentation: https://api.imgbb.com/
Imgbb does not allow you to delete images. I just tried going to the delete URL to delete the image and the image got deleted on that page but not on the other links in the JSON. If the functionality is not implemented on the site itself there is no use trying on the API. If they did have the functionality to entirely delete an image then you could have used web scraping to press the buttons.

Gatsby gatsby-remark-relative-images does not convert yaml absolute image path to relative

I am currently trying to resolve an absolute path in yaml file to relative so it can be query using graphql in gatsby. The absolute path are provided from netlify-cms.
When the same path are being placed in md file and uses gatsby-remark-relative-images to convert it to relative path, it has no problem at all, but the same does not apply to yaml.
The image file are placed in static/img/ and the path provided by cms is /img/xxx.jpg
src/data/pages/index.yaml
page: index
slider:
- image: /img/1_new.jpg
url: ""
- image: /img/2_new.jpg
url: ""
- image: /img/3_new.jpg
url: ""
gatsby-config.js
module.exports = {
// ...
plugins: [
// ...
{
resolve: `gatsby-source-filesystem`,
options: {
path: `${__dirname}/src/data`,
name: 'data',
},
},
{
resolve: 'gatsby-source-filesystem',
options: {
path: `${__dirname}/static/img`,
name: 'uploads',
},
},
{
resolve: 'gatsby-source-filesystem',
options: {
path: `${__dirname}/src/pages`,
name: 'pages',
},
},
{
resolve: 'gatsby-source-filesystem',
options: {
path: `${__dirname}/src/assets/images`,
name: 'images',
},
},
{
resolve: 'gatsby-plugin-react-svg',
options: {
rule: {
include: /\.inline\.svg$/,
},
},
},
`gatsby-plugin-sharp`,
`gatsby-transformer-sharp`,
`gatsby-transformer-yaml-plus`,
{
resolve: 'gatsby-transformer-remark',
options: {
plugins: [
{
resolve: 'gatsby-remark-relative-images',
options: {
name: 'uploads',
},
},
{
resolve: 'gatsby-remark-images',
options: {
maxWidth: 2048, // must specify max width container
},
},
{
resolve: `gatsby-remark-responsive-iframe`,
options: {
wrapperStyle: `margin-bottom: 1.0725rem`,
},
},
{
resolve: 'gatsby-remark-copy-linked-files',
options: {
destinationDir: 'static',
},
},
`gatsby-remark-smartypants`,
`gatsby-remark-widows`,
],
},
},
{
resolve: 'gatsby-plugin-netlify-cms',
options: {
modulePath: `${__dirname}/src/cms/cms.js`,
},
},
'gatsby-plugin-netlify', // make sure to keep it last in the array
],
// for avoiding CORS while developing Netlify Functions locally
// read more: https://www.gatsbyjs.org/docs/api-proxy/#advanced-proxying
developMiddleware: app => {
app.use(
'/.netlify/functions/',
proxy({
target: 'http://localhost:9000',
pathRewrite: {
'/.netlify/functions/': ``,
},
})
)
},
}
Also, here is where it convert the absolute path in node into relative path
gatsby-node.js
exports.onCreateNode = ({ node, actions, getNode }) => {
const { createNodeField } = actions
fmImagesToRelative(node) // convert image paths for gatsby images
if (node.internal.type === `MarkdownRemark`) {
const value = createFilePath({ node, getNode })
createNodeField({
name: `slug`,
node,
value,
})
}
}
Finally, here is where it define the netlify-cms configuration
static/admin/config.yml
backend:
name: git-gateway
branch: master
media_folder: static/img
public_folder: /img
collections:
- label: "Data"
name: "data"
files:
- name: "index"
label: "Index"
file: "src/data/pages/index.yml"
fields:
- {label: "Page", name: "page", widget: hidden, default: "index"}
- label: "Slider"
name: "slider"
widget: list
fields:
- {label: "Image", name: "image", widget: image}
- {label: "Url", name: "url", widget: string, required: false}
Error Message
ERROR
GraphQL Error Field "image" must not have a selection since type "String" has no subfields.
file: /home/gaara/JS/iconic-starter-netlify-cms/src/pages/index.js
1 |
2 | query IndexPage {
3 | pagesYaml(page: { eq: "index" }) {
4 | id
5 | slider {
6 | desktop {
> 7 | image {
| ^
8 | childImageSharp {
9 | fluid(maxWidth: 2000, quality: 90) {
10 | aspectRatio
11 | presentationWidth
12 | src
13 | srcSet
14 | sizes
15 | }
16 | }
17 | }
⠙ extract queries from components
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
I had already made sure that all the image exists inside the static/img/ folder. I had also made several attempt in restarting the server so to avoid image not loading issue. The image path that given from netlify-cms should stay as /img/xxx.jpg because there is a lot of other markdown files uses it and has no problem in resolving the path.
May I know is there any configuration problem which I did wrong or miss out that causing the gatsby-remark-relative-images not being able to resolve the file path?
gatsby-remark-relative-images is a plugin that only works with markdown files handled by gatsby-transformer-remark.
The recent-ish graphql schema customization update allows new solution that's independent of file types. You can explore the official docs on the topic here: Customize the Graphql Schema (gatsby docs)
Instead modifying the image paths before gatsby gets to it (like with gatsby-remark-relative-images), we'd customize the graphql schema so that the image field (slider.desktop.image in your case) resolves to the image file node instead.
Please note that the node types below are just loose examples & you should go to your graphiql endpoint (i.e. localhost:8000/graphiql) to find the correct type names.
exports.createSchemaCustomization = ({ actions }) => {
const { createTypes, createFieldExtension } = actions
createFieldExtension({
name: 'fileByStaticPath',
extend: () => ({
resolve: (src, args, ctx, info) => {
// look up original string value
const { fieldName } = info
const partialPath = src[fieldName]
// TODOS
// - join path to create the correct image file path
// - query the file node with `context.nodeModel.runQuery`
// - return the file node if exists
}
})
})
const typeDefs = `
type YamlSliderDesktop #infer {
image: File #fileByStaticPath
}
type YamlSlider #infer {
desktop: YamlSliderDesktop
}
type PagesYaml implements Node #infer {
slider: YamlSlider
}
`
createTypes(typeDefs)
}
I found myself doing this pretty often, so I wrote a plugin for it: gatsby-schema-field-absolute-path (github).
I also wrote a bit more in depth about this over here on my blog (byderek.com), but really, nothing that you won't find in the Gatsby official docs, just explained in a different language.
Hope it helps!

How can I save or update to a file after adding a new object to it?

I'm trying to update/save a js file after a forum submission.
My application is an electron / react desktop app. I have a bunch of objects saved in a .js file each object represents a help file.
HelpData.js looks similar to this.
const HelpData = [
{
name: '',
menu: '',
content: ''
},
{
name: '',
menu: '',
content: ''
},
]
export default HelpData;
My component loads in the data found in this file and pushes a new object into the array of objects. Everything works fine when the application is running, but when you exit the application the new file that was added is lost.
I need to figure out a way to save the file added to HelpData.js
Here is the function that adds the file to array of object:
handleSubmit(e) {
e.preventDefault();
let newFile = { name: '', menu: '', title: '', path: '', content: '', section: 'Section IV', video: 'n' }
newFile.name = this.state.name;
newFile.menu = this.state.menu;
newFile.title = this.state.title;
newFile.path = this.state.path;
newFile.content = this.state.content;
HelpData.(newFile);
// now that the new file has been pushed onto HelpData array, I need to save the file HelpData.js. This is what I'm not sure how to do in javascript.
}
After I push the new file into the HelpData array, how can I either rewrite HelpData.js and save the file, or write directly into the file and save?

Categories

Resources