ratty-blush
ratty-blush5mo ago

UPload Image

How to upload image using strapi4
149 Replies
kapa.ai
kapa.ai5mo ago
Hi @Sly. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave: ---------------------- You can upload images to Strapi using the mediaUploadMapper and getValueProps helper functions provided by Refine. Here is an example of how to do it:
import { Edit, useForm } from "@refinedev/antd";
import { getValueProps, mediaUploadMapper } from "@refinedev/strapi-v4";
import { Form, Upload } from "antd";

import { TOKEN_KEY, API_URL } from "../../constants";
import { IPost } from "../interfaces";

export const PostEdit: React.FC = () => {
const { formProps, saveButtonProps } = useForm<IPost>({
metaData: { populate: ["cover"] },
});

return (
<Edit saveButtonProps={saveButtonProps}>
<Form
{...formProps}
layout="vertical"
onFinish={(values) => {
formProps.onFinish?.(mediaUploadMapper(values));
}}
>
<Form.Item label="Cover">
<Form.Item
name="cover"
valuePropName="fileList"
getValueProps={(data) => getValueProps(data, API_URL)}
noStyle
>
<Upload.Dragger
name="files"
action={`${API_URL}/api/upload`}
headers={{
Authorization: `Bearer ${localStorage.getItem(TOKEN_KEY)}`,
}}
listType="picture"
multiple
>
<p className="ant-upload-text">Drag & drop a file in this area</p>
</Upload.Dragger>
</Form.Item>
</Form.Item>
</Form>
</Edit>
);
};
import { Edit, useForm } from "@refinedev/antd";
import { getValueProps, mediaUploadMapper } from "@refinedev/strapi-v4";
import { Form, Upload } from "antd";

import { TOKEN_KEY, API_URL } from "../../constants";
import { IPost } from "../interfaces";

export const PostEdit: React.FC = () => {
const { formProps, saveButtonProps } = useForm<IPost>({
metaData: { populate: ["cover"] },
});

return (
<Edit saveButtonProps={saveButtonProps}>
<Form
{...formProps}
layout="vertical"
onFinish={(values) => {
formProps.onFinish?.(mediaUploadMapper(values));
}}
>
<Form.Item label="Cover">
<Form.Item
name="cover"
valuePropName="fileList"
getValueProps={(data) => getValueProps(data, API_URL)}
noStyle
>
<Upload.Dragger
name="files"
action={`${API_URL}/api/upload`}
headers={{
Authorization: `Bearer ${localStorage.getItem(TOKEN_KEY)}`,
}}
listType="picture"
multiple
>
<p className="ant-upload-text">Drag & drop a file in this area</p>
</Upload.Dragger>
</Form.Item>
</Form.Item>
</Form>
</Edit>
);
};
In this example, the Upload.Dragger component from Ant Design is used to create a drag-and-drop area for file uploads. The action prop is set to the URL of the Strapi upload endpoint. The headers prop includes an Authorization header with a bearer token retrieved from local storage. The getValueProps function is used to get the value props for the form item, and the mediaUploadMapper function is used to map the form values for the upload. For more information, you can refer to the Strapi v4 documentation on Refine's website (https://refine.dev/docs/data/packages/strapi-v4#file-upload). ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ----------------------
kapa.ai
kapa.ai5mo ago
<@1172098337760096258> kapa.ai is still learning and improving, please let us know how it did by reacting below
ratty-blush
ratty-blush5mo ago
@kapa.ai Access to XMLHttpRequest at 'http://192.168.0.35:1340/api/upload' from origin 'http://localhost:5173' has been blocked by CORS policy: Request header field x-requested-with is not allowed by Access-Control-Allow-Headers in preflight response.
kapa.ai
kapa.ai5mo ago
Let me check the knowledge base for you. One moment! :books: ---------------------- This error is related to Cross-Origin Resource Sharing (CORS) policy. CORS is a mechanism that allows many resources (e.g., fonts, JavaScript, etc.) on a web page to be requested from another domain outside the domain from which the resource originated. In your case, it seems like your Strapi server (http://192.168.0.35:1340) is not configured to accept cross-origin requests from your client application running on http://localhost:5173. To solve this issue, you need to configure your Strapi server to allow CORS from your client application domain. Here's how you can do it: 1. Navigate to your Strapi project directory. 2. Open the config/middleware.js file. If it doesn't exist, create one. 3. Add the following configuration to the file:
module.exports = {
settings: {
cors: {
enabled: true,
origin: ['<http://localhost:5173'],>
},
},
};
module.exports = {
settings: {
cors: {
enabled: true,
origin: ['<http://localhost:5173'],>
},
},
};
In the origin array, you can add any domains that you want to allow to make cross-origin requests to your Strapi server. Please note that this is a general solution and the exact steps may vary depending on your Strapi version and setup. For more detailed information, please refer to the Strapi documentation on CORS (https://strapi.io/documentation/developer-docs/latest/setup-deployment-guides/configurations.html#middlewares). ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ----------------------
kapa.ai
kapa.ai5mo ago
<@1172098337760096258> kapa.ai is still learning and improving, please let us know how it did by reacting below
ratty-blush
ratty-blush5mo ago
@kapa.ai how to proceed, the config/middleware.js file has the folowing codes: export default [ 'strapi::errors', 'strapi::security', 'strapi::cors', 'strapi::poweredBy', 'strapi::logger', 'strapi::query', 'strapi::body', 'strapi::session', 'strapi::favicon', 'strapi::public', ];
kapa.ai
kapa.ai5mo ago
Let me check the knowledge base for you. One moment! :books: ---------------------- The config/middleware.js file you provided is not in the correct format for setting CORS configuration. It seems like you're using an array of middleware names, but to set the CORS configuration, you need to export an object with a settings property. Here's how you can modify your config/middleware.js file to allow CORS from your client application:
module.exports = {
load: {
before: ['strapi::errors', 'strapi::security', 'strapi::cors'],
order: [
"Define the middlewares' load order by putting their name in this array is the right order",
],
after: ['strapi::poweredBy', 'strapi::logger', 'strapi::query', 'strapi::body', 'strapi::session', 'strapi::favicon', 'strapi::public'],
},
settings: {
cors: {
enabled: true,
origin: ['<http://localhost:5173'],>
},
},
};
module.exports = {
load: {
before: ['strapi::errors', 'strapi::security', 'strapi::cors'],
order: [
"Define the middlewares' load order by putting their name in this array is the right order",
],
after: ['strapi::poweredBy', 'strapi::logger', 'strapi::query', 'strapi::body', 'strapi::session', 'strapi::favicon', 'strapi::public'],
},
settings: {
cors: {
enabled: true,
origin: ['<http://localhost:5173'],>
},
},
};
In this configuration, the load property defines the order in which the middlewares are loaded. The settings property is where you can set the configuration for each middleware. In this case, we're setting the cors middleware to allow requests from <http://localhost:5173.> Please note that this is a general solution and the exact steps may vary depending on your Strapi version and setup. For more detailed information, please refer to the Strapi documentation on CORS (https://strapi.io/documentation/developer-docs/latest/setup-deployment-guides/configurations.html#middlewares). ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ----------------------
kapa.ai
kapa.ai5mo ago
<@1172098337760096258> kapa.ai is still learning and improving, please let us know how it did by reacting below
ratty-blush
ratty-blush5mo ago
@kapa.ai Error: Invalid middleware configuration. Expected ││ Array<string|{name?: string, resolve?: string, config: any}
kapa.ai
kapa.ai5mo ago
Let me check the knowledge base for you. One moment! :books: ---------------------- The error message you're seeing suggests that the middleware configuration in your config/middleware.js file is not in the correct format. Strapi expects an array of strings or objects with specific properties. Here's how you can modify your config/middleware.js file to correctly set the CORS configuration:
module.exports = {
settings: {
cors: {
enabled: true,
origin: ['<http://localhost:5173'],>
},
},
};
module.exports = {
settings: {
cors: {
enabled: true,
origin: ['<http://localhost:5173'],>
},
},
};
In this configuration, the settings property is where you can set the configuration for each middleware. In this case, we're setting the cors middleware to allow requests from <http://localhost:5173.> Please note that this is a general solution and the exact steps may vary depending on your Strapi version and setup. For more detailed information, please refer to the Strapi documentation on CORS (https://strapi.io/documentation/developer-docs/latest/setup-deployment-guides/configurations.html#middlewares). ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ----------------------
kapa.ai
kapa.ai5mo ago
<@1172098337760096258> kapa.ai is still learning and improving, please let us know how it did by reacting below
exotic-emerald
exotic-emerald5mo ago
GitHub
refine/examples/data-provider-strapi-v4/src/pages/posts/create.tsx ...
A React Framework for building internal tools, admin panels, dashboards & B2B apps with unmatched flexibility. - refinedev/refine
exotic-emerald
exotic-emerald5mo ago
For cors errors, I believe you should check your Strapi dashboard Also, Just a reminder: kapa.ai is now available for free at https://refine.dev/docs! To improve our community interaction on the Refine Discord server and keep our focus on Q&A sharing, we invite you to our website to use kapa.ai.
ratty-blush
ratty-blush5mo ago
@Alican Erdurmaz Thank you, I'm trying to solve it @kapa.ai still having error ccess to XMLHttpRequest at 'http://192.168.0.35:1340/api/upload' from origin 'http://localhost:5173' has been blocked by CORS policy: Request header field x-requested-with is not allowed by Access-Control-Allow-Headers in preflight response. I modified strapi config/middleware.js file as you sugested but still not working
kapa.ai
kapa.ai5mo ago
Let me check the knowledge base for you. One moment! :books: ---------------------- I'm sorry to hear that you're still experiencing the CORS issue. The error message indicates that the 'X-Requested-With' header is not allowed by the Access-Control-Allow-Headers in the preflight response. In addition to allowing the origin, you may need to specify the headers that are allowed in the CORS configuration. Here's how you can modify your config/middleware.js file:
module.exports = {
settings: {
cors: {
enabled: true,
origin: ['<http://localhost:5173'],>
headers: ['Content-Type', 'Authorization', 'X-Requested-With', 'Origin', 'Accept'],
},
},
};
module.exports = {
settings: {
cors: {
enabled: true,
origin: ['<http://localhost:5173'],>
headers: ['Content-Type', 'Authorization', 'X-Requested-With', 'Origin', 'Accept'],
},
},
};
In this configuration, the headers property is an array of the request headers that the server will allow. I've added 'X-Requested-With' to the list, as this seems to be the header causing the issue. Please note that this is a general solution and the exact steps may vary depending on your Strapi version and setup. For more detailed information, please refer to the Strapi documentation on CORS (https://strapi.io/documentation/developer-docs/latest/setup-deployment-guides/configurations.html#middlewares). ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ----------------------