[英]POST image to strapi with other data, React
I want to allow user to post datas on strapi like name, url, description and an image.我想允许用户在 Strapi 上发布数据,例如名称、url、描述和图像。 I try to add an input type file, but I have an error 500.
我尝试添加输入类型文件,但出现错误 500。
I think this append cause I need to call localhost:1337/upload but I m not sure about this and I also use handleSubmit to post on localhost:1337/links.我认为这个 append 因为我需要调用 localhost:1337/upload 但我对此不确定,我也使用 handleSubmit 在 localhost:1337/links 上发布。 So I ma bit confused about it....
所以我对此有点困惑......
So can you help me to fix this please?那么你能帮我解决这个问题吗?
import React, { useState } from "react";
import {
Button,
FormControl,
FormLabel,
Input,
Checkbox,
VStack,
Select,
Heading,
Textarea,
} from "@chakra-ui/react";
import { useSelector } from "react-redux";
import axios from "axios";
const backendUrl = process.env.REACT_APP_API_URL;
export default function AddLinkView() {
const { user } = useSelector((state) => state.user);
console.log(user.id)
const token = localStorage.getItem("jwt");
const [inputs, setInputs] = useState({});
const handleChange = (e) => {
const name = e.target.name;
const value = e.target.value;
setInputs((values) => ({ ...values, [name]: value }));
};
const randomNumberForSlug = Math.floor(Math.random() * 10000);
console.log(randomNumberForSlug);
const handleSubmit = async (e) => {
e.preventDefault();
await axios
.post(
`${backendUrl}/api/links`,
{
data: {
userid: user.id,
slug: inputs.name.replace(/\W+/g, "-") + "-" + randomNumberForSlug,
...inputs,
},
},
{ headers: { Authorization: `Bearer ${token}` } }
)
.then((response) => {
console.log(response);
})
.catch((error) => {
console.log(error);
});
};
return (
<>
<form onSubmit={handleSubmit}>
<FormControl bg="white" p={6} rounded="xl" >
<Heading as="h1" size="xl" pb={6}>
Ajouter un article
</Heading>
<VStack spacing={2} align="stretch" w="75%">
<FormLabel>URL</FormLabel>
<Input
bg="white"
type="text"
name="url"
placeholder="Add your URL"
value={inputs.url || ""}
onChange={handleChange}
/>
<FormLabel>Titre</FormLabel>
<Input
bg="white"
type="text"
name="name"
placeholder="Name"
value={inputs.name || ""}
onChange={handleChange}
/>
<FormLabel>Image</FormLabel>
<Input
type="file"
name="featuredimg"
placeholder="Featured Image"
value={inputs.featuredimg || ""}
onChange={handleChange}
/>
<FormLabel>Description </FormLabel>
<Textarea
bg="white"
type="textarea"
name="body"
placeholder="Add your description"
value={inputs.body || ""}
onChange={handleChange}
/>
<FormLabel>Type</FormLabel>
<Select
placeholder="Select option"
name="type"
onChange={handleChange}
>
<option value="lien">lien</option>
<option value="image">image</option>
<option value="video">video</option>
</Select>
<FormLabel>Votre lien est pour un public adulte ?</FormLabel>
<Checkbox
colorScheme="red"
bg="white"
type="checkbox"
name="nsfw"
placeholder="nsfw"
value={true || false}
onChange={handleChange}
>
Adult only
</Checkbox>
<FormLabel>Rendre ce lien privé</FormLabel>
<Checkbox
colorScheme="red"
bg="white"
type="checkbox"
name="public"
placeholder="public"
value={true || false}
onChange={handleChange}
>
Private link
</Checkbox>
<Button
colorScheme="green"
type="submit"
w={{ base: "100%", md: "max-content" }}
>
Submit
</Button>
</VStack>
</FormControl>
</form>
</>
);
}
This is my solution这是我的解决方案
import React, { useState } from "react";
import {
Button,
FormControl,
FormLabel,
Input,
Checkbox,
VStack,
Select,
Heading,
Textarea,
} from "@chakra-ui/react";
import { useSelector } from "react-redux";
import axios from "axios";
const backendUrl = process.env.REACT_APP_API_URL;
export default function AddLinkView() {
const { user } = useSelector((state) => state.user);
console.log(user.id);
const token = localStorage.getItem("jwt");
const [inputs, setInputs] = useState({});
const handleChange = (e) => {
const name = e.target.name;
const value = e.target.value;
setInputs((values) => ({ ...values, [name]: value }));
};
const handleImgChange = (e) => {
setInputs({ featuredimg: e.target.files[0] });
};
console.log(inputs.featuredimg);
const randomNumberForId = Math.floor(Math.random() * 100000);
const formData = new FormData();
formData.append("files", inputs.featuredimg);
formData.append("ref", "api::link.link");
formData.append("refId", randomNumberForId);
formData.append("field", "featuredimg");
const randomNumberForSlug = Math.floor(Math.random() * 10000);
console.log(randomNumberForSlug);
const handleSubmit = async (e) => {
e.preventDefault();
await axios.post(
`${backendUrl}/api/links`,
{
data: {
userid: user.id,
slug: inputs.name.replace(/\W+/g, "-") + "-" + randomNumberForSlug,
name: inputs.name,
url: inputs.url,
body: inputs.body,
type: inputs.type,
nsfw: inputs.nsfw,
public: inputs.public,
id: randomNumberForId,
tag: [
{
name: inputs.tag,
},
],
},
},
{ headers: { Authorization: `Bearer ${token}` } }
);
//! Need to fix this part
await axios
.post(
`${backendUrl}/api/upload`,
formData,
{
headers: {
Authorization: `Bearer ${token}`,
"Content-Type": "multipart/form-data",
},
}
)
.then((response) => {
console.log(response);
})
.catch((error) => {
console.log(error);
});
};
return (
<>
<form onSubmit={handleSubmit}>
<FormControl bg="white" p={6} rounded="xl">
<Heading as="h1" size="xl" pb={6}>
Ajouter un article
</Heading>
<VStack spacing={2} align="stretch" w="75%">
<FormLabel>URL</FormLabel>
<Input
bg="white"
type="text"
name="url"
placeholder="Add your URL"
value={inputs.url || ""}
onChange={handleChange}
/>
<FormLabel>Titre</FormLabel>
<Input
bg="white"
type="text"
name="name"
placeholder="Name"
value={inputs.name || ""}
onChange={handleChange}
/>
<FormLabel>Tag</FormLabel>
<Input
bg="white"
type="text"
name="tag"
placeholder="Tag"
value={inputs.tag || ""}
onChange={handleChange}
/>
<FormLabel>Image</FormLabel>
<Input
type="file"
name="featuredimg"
placeholder="Featured Image"
bg="white"
border="none"
// value={inputs.featuredimg || ""}
onChange={handleImgChange}
/>
{/* <input type="text" name="ref" value="api::links.links" />
<input type="text" name="refId" value="5c126648c7415f0c0ef1bccd" /> */}
<FormLabel>Description </FormLabel>
<Textarea
bg="white"
type="textarea"
name="body"
height={200}
placeholder="Utiliser le markdown pour formater votre texte
Pour faire un lien, utiliser la syntaxe : [titre du lien](url du lien)
Pour faire une image, utiliser la syntaxe : ![titre de l'image](url de l'image)
Pour faire un titre, utiliser la syntaxe : # titre du titre
Pour faire un sous-titre, utiliser la syntaxe : ## sous-titre du sous-titre
Pour faire un paragraphe, utiliser la syntaxe : paragraphe du paragraphe
"
value={inputs.body || ""}
onChange={handleChange}
/>
<FormLabel>Type</FormLabel>
<Select
placeholder="Sélectionnez un type"
name="type"
onChange={handleChange}
>
<option value="lien">lien</option>
<option value="image">image</option>
<option value="video">video</option>
</Select>
<FormLabel>Votre lien est pour un public adulte ?</FormLabel>
<Checkbox
colorScheme="red"
bg="white"
type="checkbox"
name="nsfw"
placeholder="nsfw"
value={true || false}
onChange={handleChange}
>
Lien adulte
</Checkbox>
<FormLabel>Rendre ce lien privé</FormLabel>
<Checkbox
colorScheme="red"
bg="white"
type="checkbox"
name="public"
placeholder="public"
value={true || false}
onChange={handleChange}
>
Lien privé
</Checkbox>
<Button
colorScheme="green"
type="submit"
w={{ base: "100%", md: "max-content" }}
>
Publier
</Button>
</VStack>
</FormControl>
</form>
</>
);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.