Sending a post request image through form data in React Native JavaScript with axios

Viewed 1294

I am having an issue with sending an image in a post request through axios using a form in a react native app of mine, and would love a bit of advice on this!

The backend runs with Python Flask, the same post requests (submitting an image with an 'image' key through a form) work fine with PostMan and other API tests, as do get requests from the react-native front-end.

However, when attempting to do the same from react-native javascript, I get the following error from the back-end:

400 Bad Request: The browser (or proxy) sent a request that this server could not understand.

Here's my front-end code

import React from 'react';
import axios from 'axios';
import { View, StyleSheet, SafeAreaView, Text, Image, TouchableOpacity, ScrollView, TextInput } from 'react-native';
import image02 from '../assets/images/carrot.jpg'

formData.append('image',
      {
         uri: "file:://../assets/images/carrot.jpg",
         name:'carrot.jpg',
         type:'image/jpg'
      }
);

formData.append('test',  image02);

export function App() {
  const postDataSimple = () => {
    axios
        .post('http://192.168.0.11:5000/get_progress', formData, {
            headers: {
              'Content-Type': 'multipart/form-data',
            }
        })
        .then(function (response) {
            // handle success
            alert(JSON.stringify(response.data));
        })
        .catch(function (error) {
            // handle error
            alert(error.message);
        })
        .finally(function () {
            // always executed
            console.log(formData);
            console.log(formData.get('test'));
            console.log(formData.get('image'));
        })
    };
  return (
      <View>
        <Text style={{fontSize: 30, textAlign: 'center'}}>
          Example of Axios Networking in React Native
        </Text>
        {/*Running POST Request*/}
        <TouchableOpacity
          style={styles.buttonStyle}
          onPress={postDataSimple}>
          <Text>Simple Post</Text>
        </TouchableOpacity>
      </View>
  )
}

const styles = StyleSheet.create({
  container: {
    justifyContent: 'center',
    flex: 1,
    padding: 16,
  },
  buttonStyle: {
    alignItems: 'center',
    backgroundColor: '#DDDDDD',
    padding: 10,
    width: '100%',
    marginTop: 16,
  },
});

export default App;

I have tried various ways of getting the image too: replacing the uri:"file:://..." with uri:require('../assets/images/carrot.jpg'); and also, as you may see from the snippet, sending the image with&without name/type tags. Yet I always end with the same error.

And the relevant python back-end code:

from flask import Flask, send_file, request, jsonify
app = Flask(__name__)

@app.route('/get_progress', methods = ['POST'])
def get_progress():
    try:
        new_file = request.files['image'].read()
    except Exception as e:
        response = jsonify({'value':"N/A", 'message':"ERR: image not part of form", 'error':str(e), 'recieved':str(request), 'files/form':str(request.files)})
        response.headers.add('Access-Control-Allow-Origin', '*')
        return response

    response = jsonify({"value":"success!!!"})
    response.headers.add('Access-Control-Allow-Origin', '*')    
    return response

if __name__ == '__main__':
    app.run(host='192.168.0.11', port=5000, debug=True)

When looking at the console.log commands of axios.finally in the browser, FormData comes out FormData {}, formData.get('test') comes out successfully as a path to an image (localhost:19006/static/media/carrot.7382658d.jpg) and formData.get('image') comes out as [object Object]

0 Answers
Related