other-emerald
other-emerald12mo ago

Strapi v4 Data Provider Example

Hello, I got problem with file uploading. I downloaded your example and made collection in strapi admin panel. My problem is that the refine - client, can get image files when I make new record in database using strapi CMS but when i want to post some files through refine I got an error.
7 Replies
kapa.ai
kapa.ai12mo ago
Hi @sensib0i. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave: ---------------------- I'm sorry to hear that you're having trouble with file uploading in refine. Based on the information provided, it's hard to pinpoint the exact issue without more details. However, I can provide some general guidance on how to handle file uploads with refine and Strapi. Firstly, ensure that you're using the correct endpoint for file uploads. In the examples provided, the endpoint used is ${API_URL}/api/upload. Replace API_URL with your Strapi server's URL. Secondly, make sure you're sending the correct headers with your request. In the examples, an Authorization header is included with a Bearer token. This token should be the JWT token you get when you authenticate with your Strapi server. Here's an example of how to handle file uploads with refine and Strapi:
import { useState } from "react";
import axios from "axios";
import { Edit, useForm } from "@refinedev/mantine";
import { Text } from "@mantine/core";
import { Dropzone, IMAGE_MIME_TYPE, FileWithPath } from "@mantine/dropzone";

const API_URL = "<http://localhost:1337";>
const TOKEN_KEY = "strapi-jwt-token";

export const PostEdit: React.FC = () => {
const [isUploadLoading, setIsUploadLoading] = useState(false);

const { saveButtonProps, setFieldValue } = useForm<any>({
initialValues: {
title: "",
cover: "",
},
});

const handleOnDrop = async (files: FileWithPath[]) => {
try {
setIsUploadLoading(true);

const formData = new FormData();

const file = files[0];

formData.append("files", file);

const res = await axios.post(`${API_URL}/api/upload`, formData, {
headers: {
Authorization: `Bearer ${localStorage.getItem(TOKEN_KEY)}`,
},
});

setFieldValue("cover", res.data[0].id);

setIsUploadLoading(false);
} catch (error) {
setIsUploadLoading(false);
}
};

return (
<Edit saveButtonProps={saveButtonProps}>
<form>
<Text mt={8} weight={500} size="sm" color="#212529">
Cover
</Text>
<Dropzone
accept={IMAGE_MIME_TYPE}
onDrop={handleOnDrop}
loading={isUploadLoading}
>
<Text align="center">Drop images here</Text>
</Dropzone>
</form>
</Edit>
);
};
import { useState } from "react";
import axios from "axios";
import { Edit, useForm } from "@refinedev/mantine";
import { Text } from "@mantine/core";
import { Dropzone, IMAGE_MIME_TYPE, FileWithPath } from "@mantine/dropzone";

const API_URL = "<http://localhost:1337";>
const TOKEN_KEY = "strapi-jwt-token";

export const PostEdit: React.FC = () => {
const [isUploadLoading, setIsUploadLoading] = useState(false);

const { saveButtonProps, setFieldValue } = useForm<any>({
initialValues: {
title: "",
cover: "",
},
});

const handleOnDrop = async (files: FileWithPath[]) => {
try {
setIsUploadLoading(true);

const formData = new FormData();

const file = files[0];

formData.append("files", file);

const res = await axios.post(`${API_URL}/api/upload`, formData, {
headers: {
Authorization: `Bearer ${localStorage.getItem(TOKEN_KEY)}`,
},
});

setFieldValue("cover", res.data[0].id);

setIsUploadLoading(false);
} catch (error) {
setIsUploadLoading(false);
}
};

return (
<Edit saveButtonProps={saveButtonProps}>
<form>
<Text mt={8} weight={500} size="sm" color="#212529">
Cover
</Text>
<Dropzone
accept={IMAGE_MIME_TYPE}
onDrop={handleOnDrop}
loading={isUploadLoading}
>
<Text align="center">Drop images here</Text>
</Dropzone>
</form>
</Edit>
);
};
(Source: refine.dev/docs (https://refine.dev/docs/packages/documentation/data-providers/strapi-v4)) If you're still having trouble, it would be helpful to know the exact error message you're receiving. ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ----------------------
kapa.ai
kapa.ai12mo ago
<@667849704293269515> kapa.ai is still learning and improving, please let us know how it did by reacting below
other-emerald
other-emerald12mo ago
@kapa.ai I doesn't give me nothing. I just got your example repo cloned on my local machine, so we base on the same resource. (also I choosen Ant Design instead of Mantine in your example). Thats the error I got notification in client side: 1 relation(s) of type plugin::upload.file associated with this entity do not exist There was an error creating company (status code: 400) Also when I check Network tab in Developer browser Tools I have there an error of type xhr that has following response in header (raw format) HTTP/1.1 400 Bad Request Content-Security-Policy: connect-src 'self' https:;img-src 'self' data: blob: https://market-assets.strapi.io;media-src 'self' data: blob:;default-src 'self';base-uri 'self';font-src 'self' https: data:;form-action 'self';frame-ancestors 'self';object-src 'none';script-src 'self';script-src-attr 'none';style-src 'self' https: 'unsafe-inline' Referrer-Policy: no-referrer Strict-Transport-Security: max-age=31536000; includeSubDomains X-Content-Type-Options: nosniff X-DNS-Prefetch-Control: off X-Download-Options: noopen X-Frame-Options: SAMEORIGIN X-Permitted-Cross-Domain-Policies: none Vary: Origin Access-Control-Allow-Origin: http://localhost:5173 Access-Control-Allow-Credentials: true Content-Type: application/json; charset=utf-8 Content-Length: 311 Date: Sat, 19 Aug 2023 08:08:30 GMT Connection: keep-alive Keep-Alive: timeout=5
kapa.ai
kapa.ai12mo ago
Let me check the knowledge base for you. One moment! :books: ---------------------- I'm sorry to hear that you're still having trouble. The error message you're seeing suggests that there might be an issue with the relationship between the entity you're trying to create and the file you're trying to upload. In Strapi, when you create a relation with the upload plugin, it creates a relation in the database. The error message suggests that this relation does not exist. This could be due to a misconfiguration in your Strapi setup. Here are a few things you could check: 1. Check your Strapi model configuration: Ensure that the model you're trying to create has a relation with the upload plugin. This is usually defined in the model's settings JSON file in Strapi. 2. Check the data you're sending in your request: When you're creating a new entity and want to associate a file with it, you need to send the ID of the uploaded file. In the example code, this is done with setFieldValue("cover", res.data[0].id);. Make sure that the file is being uploaded correctly and that you're sending the correct file ID. 3. Check your Strapi server logs: There might be more information about the error in your Strapi server logs. This could give you more insight into what's going wrong. If you're still having trouble, I would recommend reaching out to the Strapi community or checking the Strapi documentation (https://docs.strapi.io/developer-docs/latest/getting-started/introduction.html) for more information. ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ----------------------
kapa.ai
kapa.ai12mo ago
<@667849704293269515> kapa.ai is still learning and improving, please let us know how it did by reacting below
other-emerald
other-emerald12mo ago
Ok, it was a strapi cors configuration problem. Theres a solution if someone have same problem. https://stackoverflow.com/questions/71382302/setting-cors-in-strapi-4
Stack Overflow
Setting cors in strapi 4
I'm using strapi 4 as localhost and got a problem with cors settings when I add new assets via url Image upload takes CORS error Access to XMLHttpRequest at 'https://www.countrysideveterinaryclinic...
extended-salmon
extended-salmon12mo ago
Hey @simbafs, You can also check these examples https://refine.dev/docs/examples/?tags=upload,antd