skip to Main Content
import React,  { useState } from 'react';
import { Text, View, StyleSheet, Image } from 'react-native';
import Constants from 'expo-constants';

// You can import from local files
import AssetExample from './components/AssetExample';

// or any pure javascript modules available in npm
import { Card } from 'react-native-paper';
import * as FileSystem from 'expo-file-system';

export default function App() {

  let data = new FormData();

  let url="https://uploadfilesserver.eugenevolkov.repl.co/upload"

  data.append("content",{type:'image/jpeg', uri:'https://snack-code-uploads.s3.us-west-1.amazonaws.com/~asset/201a148e3d40baa81d8ef06e316b5ca2', name:'ball.jpg'} )

  function upload(){

    fetch(url, {
      method: "post",
      headers: {
        "Content-Type": "multipart/form-data",
      },
      body: data,
    })

      .then(res => {res.json()

              // console.log('res',res)
            }
      )
      .then(final => {

        console.log(
          "Success")}

      )

    //    .catch(err => {
    //   console.error("error uploading images: ", err);
    // });

  }


  upload()



  return (
    <View style={styles.container}>
      <Text style={styles.paragraph}>
        Image to upload
      </Text>
      <Card>
        <Image  source={require('./ball_1.jpg')}/>
      </Card>
    </View>
  );
}

I am new to react native. The fetch always results in two uploads (two POST requests). There is no OPTIONS request. In the backend (Django) upload folder there are always 2 ‘ball.jpg’ files. The same issue happens after building the app.

3

Answers


  1. Chosen as BEST ANSWER

    Defining function as async fixed it.

        async function upload(){
        
               await fetch(url, {
                
                        method: "post",
                        headers: {
                                "Content-Type": "multipart/form-data",
                        },
                        body: data,
                              })
              .then(res => {
                   res.json()
                   console.log("Success")
        
               })       
         }
    
    upload()
    

  2. Try to use then() only one time :

    function upload(){
          fetch(url, {
                    method: "post",
                    headers: {
                            "Content-Type": "multipart/form-data",
                    },
                    body: data,
          })
          .then(res => {
               res.json()
               console.log("Success")
           })
    
     }
    
    Login or Signup to reply.
  3. For the React Native IOS platform, you must send a URL without the ‘file://’ prefix. I believe it could be the same as Expo. It can be used when used with a file or picture picked from your mobile.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search