Skip to content

Instantly share code, notes, and snippets.

@phuochau
Last active April 19, 2019 02:12
Show Gist options
  • Save phuochau/53dd787c721b2a9e241c5e14ba4029fc to your computer and use it in GitHub Desktop.
Save phuochau/53dd787c721b2a9e241c5e14ba4029fc to your computer and use it in GitHub Desktop.
Request multipart with rn-fetch-blob (Android doesn't allow number in param)
/**
* A file must have structure as below:
* {
* name: 'file'
* content: {
* uri: 'file://abc',
* data: 'file body', only use uri or data
* name: 'avatar.jpg',
* type: 'image/jpg'
* }
* }
*/
requestMultipart = (method, uri, files, data = {}, useToken = true, extHeaders = {}) => {
const headers = extHeaders
if (useToken && this.authorizationToken) {
headers['Authorization'] = this.authorizationToken
}
if (this.contentLang) {
headers['content-language'] = this.contentLang
}
const formData = []
for (const key in data) {
formData.push({
name: key,
// this line is important
data: Platform.OS === 'android' && typeof(data[key]) === 'number' ? data[key].toString() : data[key]
})
}
for (let i = 0; i < files.length; i++) {
const file = files[i]
if (file.content.data) {
formData.push({
name: file.name,
filename: file.content.name,
type: file.content.type,
data: file.content.data
})
} else {
formData.push({
name: file.name,
filename: file.content.name,
type: file.content.type,
data: RNFetchBlob.wrap(file.content.uri.replace('file://', ''))
})
}
}
const url = `${Config.API_ENDPOINT}${uri}`
return RNFetchBlob.fetch(method, url, headers, formData)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment