1 year ago

#380056

test-img

Shariq Ahmed

React Native File Upload not working using Axios

I am trying to upload a file to the server and the server APIs are written using django. The file upload is working perfectly from Postman but when i try to upload from mobile app (React Native) using axios the backend is not able to read it.

Following is the Frontend Snippet:

let accessToken = await AsyncStorage.getItem('accessToken')
let formData = new FormData()
formData.append('doc_type', this.state.selectedDoc.id)
formData.append('document', this.state.selectedFiles) // <- This is the fetched file in array format . [{filname:'abc', size:12344,.....}]
formData.append('description', this.state.description.value)
formData.append('data', JSON.stringify(this.state.selectedDoc.fields))

let url = `${AppConstants.url}api/${AppConstants.apiVersion}/upload_doc`
        var config = {
            method: 'post',
            url: url,
            data: formData,
            headers: {
                'Authorization': `Bearer ${accessToken}`,
            }
        }
        axios(config)
            .then((resp) => {
                resolve(resp)
            })
            .catch((err) => {
                reject(err)
            });

And the backend-end if else statement is as follows:

if(request.FILES.getlist("document")):
        files = request.FILES.getlist("document")
        ....
        ....
        ....
else:
        return response.JsonResponse({
                    'success' : False,
                    'message' : 'Please Upload a file'
                }, status = status.HTTP_200_OK)

The above else block is executed even though the UI is sending a valid file.

Request you to please share a solution.

reactjs

django

react-native

axios

multipartform-data

0 Answers

Your Answer

Accepted video resources