Perhaps one of the hardest things to do, and that is to figure out how to upload an image to strapi,
and to link it to a specific content type.
On the official docs there is no mentioning of how to do it clearly, they only have an example on how to upload
a file to media and it's done with just javascript and HTML in the browser, and if you have tried uploading an image to strapi
form a react app or vue that clearly doesn't work.
But don't worry I have gone ahead and figured out how to make it work, so I am going to walk you through how to do it !
1- Let's add Axios to our react app
yarn add axios
or
npm install axios --save
To upload files to strapi you'll have to use the upload endpoint
If you are running it locally it will look like this
// Strapi v4
http:localhost:1337/api/upload
// Strapi v3
http:localhost:1337/upload
It will be a POST request
2- Add an input
import { useState } from 'react';
import axios from 'axios';
function App() {
const [files,setFiles] = useState()
const uploadImage = async () => {
//posting logic will go here
}
return (
<form onSubmit={uploadImage}>
<input
type="file"
onChange={(e)=>setFiles(e.target.files)}
/>
<input type="submit" value="Submit" />
</form>
);
}
we'll add an input field of type file and capture the event with the onChange prop,
we are setting e.target.files to the state called files, this basically the information we need
to upload our file.
We are also adding a function for onSubmit where will create the logic for adding an image.
3- Uploading the image
const uploadImage = async (e) => {
e.preventDefault();
const formData = new FormData()
formData.append('files', files[0])
axios.post("http://localhost:1337/upload", formData)
.then((response)=>{
//after success
}).catch((error)=>{
//handle error
})
}
First we prevent the default behaviour of the submit button so our page wouldn't refresh,
then we create an instance of FormData.
We have to use FormData or else it wouldn't work, using json format will not be possible in this case.
We append files[0] to the formData and we call it files, make sure to use the same key files
Then pass formData to axios.post second param, and after you press submit an image will be uploaded to the media on Strapi.
4- Link image to a content type
const uploadImage = async (e) => {
e.preventDefault();
const formData = new FormData()
formData.append('files', files[0])
axios.post("http://localhost:1337/upload", formData)
.then((response)=>{
const imageId = response.data[0].id
axios.post("http://localhost:1337/people",{image:imageId}).then((response)=>{
//handle success
}).catch((error)=>{
//handle error
})
}).catch((error)=>{
//handle error
})
}
I created a content type called Person (People because strapi is smart enough to make it plural),
I added an single image field to it.
All we need to do is get the image id that we successfully uploaded beforehand and after that we add the image id to
our POST request on the image field, and after that everything should be linked and your content type will have the image in it's field.
I hope this was helpful, and please checkout the Strapi website to learn more about it !
Follow me on my social media accounts to recieve more content !
Thanks for the support !
Top comments (11)
Thanks Bassel it's really helpful. Just to add a little, for strapi v4 in url you must include
/api
endpoint, suchhttp://localhost:1337/api/upload
. Otherwise it will throw an error.Thanks a lot for this article men, this issue almost makes me crazy😅
Hi, do you believe the same process in react native will work?
The process concerning Strapi yes, However React Native probably uses a different way to get the files from a mobile phone.
where strapi saves the photos? to the folder that can be committed to git?
Yes Strapi does save photos by default to a folder that can be committed with git, however I recommend you use a cloud storage provider, the same method will work. You just need to setup the storage provider with Strapi
Hi Bassel after doing this giving response 400 (Bad Request) opening the network tab and i see no data sent just nulll do you know where the problem may locate
Hello Amr, I am with the same problem (Bad Request). But if I use just /upload, without the api, I then get an Unauthorized.
Did you solve this?
Hi Mauricio, yes i solved this problem by using axios like this
and don't forget to check upload permission in strapi users panel for public if you want to upload with authenticated users send token in the headers with the post request.
Hello yes the new version of Strapi, the V4 version needs to be
api/upload
I will try to update the post to follow the new version
Thanks @bassel17 ...! but i want to help in add image with caption is it possible in strapi v4 ?