John
John

Reputation: 43

How to upload a file in react-native iOS?

While trying to upload a file I ran into an issue on iOS, the code works fine on android. After a bit of googling, I found that it is a known issue in react-native iOS and has a bug report submitted. This is the issue. I want to know if there is any other way to upload files on iOS. Below is the snippet of code I'm using. Please let me know if there is something that can be done.

const resp = await fetch(uploadUrl, {
    method: 'POST',
    headers: {
        'content-type': 'multipart/form-data',
    },
    body: file, // file is File type
});

Upvotes: 2

Views: 2157

Answers (1)

Mehroze Yaqoob
Mehroze Yaqoob

Reputation: 1041

You can something like below code snippet

function uploadProfileImage(image, token) {
  const url = ServiceUrls.UPLOAD_PROFILE_IMAGE

  return uploadResourceWithPost({
    url,
    authToken: token,
    formData: createFormData(image),
  })
}


const createFormData = (data) => {
  const form = new FormData()
  form.append('file', {
    uri: Platform.OS === 'android' ? data.uri : data.uri.replace('file://', ''),
    type: 'image/jpeg',
    name: 'image.jpg',
  })
  return form
}

const uploadResourceWithPost = ({ url, authToken, formData }) => {
  return handleResponse(axios.post(url, formData, defaultUploadOptions(authToken)))
}

const defaultUploadOptions = (authToken) => ({
  timeout,
  headers: {
    'X-Auth-Token': authToken,
    'Content-Type': 'multipart/form-data',
  },
})


const handleResponse = (responsePromise) => {
  return NetInfo.fetch().then((state) => {
    if (state.isConnected) {
      return responsePromise
        .then((response) => {
          return ResponseService.parseSuccess(response)
        })
        .catch((error) => {
          return ResponseService.parseError(error)
        })
    }

    return {
      ok: false,
      message: 'Check your network connection and try again.',
      status: 408,
    }
  })
}

const parseSuccess = ({ data, headers }) => ({ ...data, headers, ok: true })

const parseError = ({ response }) => {
  let message = 'Check your network connection and try again.'
  let status = 408
  if (response && response.data) {
    const { data } = response
    message = data.message
    status = data.code
  }

  return { status, message }
}

Upvotes: 1

Related Questions