Created
June 6, 2019 13:55
-
-
Save alexandrebodin/d69fc465fb731b665429f6da472929df to your computer and use it in GitHub Desktop.
Uploading images to strapi with react and axios
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { Component } from 'react'; | |
import axios from 'axios'; | |
import './App.css'; | |
class App extends Component { | |
constructor() { | |
super(); | |
this.state = { | |
images: [], | |
}; | |
} | |
onImageChange = event => { | |
console.log(event.target.files); | |
this.setState({ | |
images: event.target.files, | |
}); | |
}; | |
onSubmit = e => { | |
e.preventDefault(); | |
const formData = new FormData(); | |
Array.from(this.state.images).forEach(image => { | |
formData.append('files', image); | |
}); | |
axios | |
.post(`http://localhost:1337/upload`, formData, { | |
headers: { 'Content-Type': 'multipart/form-data' }, | |
}) | |
.then(res => { | |
console.log(res); | |
}) | |
.catch(err => { | |
console.log(err); | |
}); | |
}; | |
render() { | |
return ( | |
<div className="App"> | |
<form onSubmit={this.onSubmit}> | |
<input | |
type="file" | |
name="files" | |
onChange={this.onImageChange} | |
alt="image" | |
/> | |
<br /> | |
<button type="submit">Send</button> | |
</form> | |
</div> | |
); | |
} | |
} | |
export default App; |
What version of Strapi are you using? I seem to be getting a error 500.
bad content-type header, no multipart boundary
Use the below code:
const myHeaders = new Headers();
myHeaders.append('Authorization', 'Bearer '+token);
let result = await fetch('http://localhost:1337/upload',{
body: data,
headers:myHeaders,
method: "POST",
timeout: 30000}).then(response => response.json());
Remove
{ 'Content-Type': 'multipart/form-data' }`How do we tell where the token is defined because in my application it is giving an error that token is not defined.
The token is received after authentication auth/local, you either store it in a session or localstorage, then you use it in your application. i.e let token=AsyncStorage.getItem("token saved name")
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
How do we tell where the token is defined because in my application it is giving an error that token is not defined.