Last active
January 3, 2024 12:52
-
-
Save jakehasler/0b04b7e143b37c47111c2594120f45bd to your computer and use it in GitHub Desktop.
POST an image as `multipart/form-data`
This file contains hidden or 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
// Function form the react-native-image-picker library | |
ImagePicker.showImagePicker({ title: 'Select Image' }, (response) => { | |
// format the image data | |
const image = { | |
uri: response.uri, | |
type: 'image/jpeg', | |
name: 'myImage' + '-' + Date.now() + '.jpg' | |
} | |
// Instantiate a FormData() object | |
const imgBody = new FormData(); | |
// append the image to the object with the title 'image' | |
body.append('image', image); | |
const url = `http://your-api.com/image-upload`; | |
// Perform the request. Note the content type - very important | |
fetch(url, { | |
method: 'POST', | |
headers: { | |
'Accept': 'application/json', | |
'Content-Type': 'multipart/form-data', | |
}, | |
body: imgBody | |
}).then(res => res.json()).then(results => { | |
// Just me assigning the image url to be seen in the view | |
const source = { uri: res.imageUrl, isStatic: true }; | |
const images = this.state.images; | |
images[index] = source; | |
this.setState({ images }); | |
}).catch(error => { | |
console.error(error); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
hello.
so it's mean you first upload an image to the server and then it'd return an src for this image, so send the src to Backend, then save it to db?