Reputation: 27
I'm doing a post request to my strapi and its working to some extent, but I'm not able to link my file (image) to the same entry creation. I only get the formDataToSend
to show up in the strapi when I submit the form.
const [files,setFiles] = useState()
async function onSubmit(data) {
setSubmitting(true);
setError(null);
let formDataToSend= {
name: data.name,
description: data.description,
}
axios.post(BASE_URL, formDataToSend)
.then(res =>{
console.log(res.data)
return res.data.id
})
.then(refId =>{
const formData = new FormData();
formData.append("files", files[0]);
formData.append("refId", refId);
formData.append("ref", "example");
return axios.post(BASE_URL +"upload", formData)
})
.then(res =>{
console.log("success", res.data);
})
.catch(error =>{
console.log(error)
})
}
return(
<Form>
<Form.Control type="file" {...register("image")} name="image" onChange=
{(e)=>setFiles(e.target.files)} />
</Form>
)
When I log the response for both of them it shows the file is uploaded but it's not linked to this entry, and I can see it in the strapi media library as well.
{
id: "614104c3c3ded200165081f4"
mime: "image/jpeg"
name: "example_image.jpg"
provider: "cloudinary"
provider_metadata: {public_id: 'example_image', resource_type: 'image'}
related: []
size: 37.52
url: "cloudinaryurlexample.com"
}
{
description: "example description"
id: "614104c0c3ded200165081f3"
name: "example name"
}
any pointers to what I'm doing wrong and how to achieve this are really appreciated!
Upvotes: 1
Views: 5728
Reputation: 4506
Well, to link uploaded files against a particular entry following parameters are mandatory:
As per the question you posted above, it's clear that you're missing the field
key in your request params. This key should contain the column/field name of the collection where the uploaded file data will be linked.
const [files,setFiles] = useState()
async function onSubmit(data) {
setSubmitting(true);
setError(null);
let formDataToSend= {
name: data.name,
description: data.description,
}
axios.post(BASE_URL, formDataToSend)
.then(res =>{
console.log(res.data)
return res.data.id
})
.then(refId =>{
const formData = new FormData();
formData.append("files", files[0]);
formData.append("refId", 1);
formData.append("ref", "restaraunt");
formData.append("field", "restaraunt_logo");
return axios.post(BASE_URL +"upload", formData)
})
.then(res =>{
console.log("success", res.data);
})
.catch(error =>{
console.log(error)
})
}
return(
<Form>
<Form.Control type="file" {...register("image")} name="image" onChange=
{(e)=>setFiles(e.target.files)} />
</Form>
)
As per this, it will first upload the file to media gallery and then look for a collection called restaraunt
and then update the data in the restaraunt_logo
column/field of restaraunt
collection.
Upvotes: 2