Home > Net >  formData problems using fetch to attempt image upload
formData problems using fetch to attempt image upload

Time:12-31

I am attempting to upload an image from React Native to a server. I have used a 'picker' (react-native-document-picker) to select the image and that part seems to be functional. Here is the code I am working with:

import React, { Component } from "react";
import { Button, Dimensions, Image, Platform, SafeAreaView, ScrollView, StyleSheet, Text, TextInput, TouchableOpacity, View } from "react-native";

import DocumentPicker from 'react-native-document-picker';

const SERVER_URL = 'http://localhost:3000';

export default class Images extends Component {
constructor(props) {
  super(props);

  this.state = {
    photo: null,
  };
}

   ChoosePhoto = async () => {

    try {

    const res = await DocumentPicker.pickSingle({ type: [DocumentPicker.types.images], });

    this.setState({ photo: res });  //Set the state to the selected file attributes

    } catch (err) {
    this.setState({ photo: null });
  
      if (DocumentPicker.isCancel(err)) {
        alert('Canceled');  //user canceled the document selection
      } else {
        alert('Selection Error: '   JSON.stringify(err));  //Unknown Error
      }  //Handling any exception (if any)

    }  //try routine

  };

  UploadPhoto = async () => {

   if (this.state.photo != null) {

   //if file selected then create FormData

   const fileToUpload = this.state.photo.uri;

   const data = new FormData();
   data.append('name', 'Image Upload');
   data.append('type', this.state.photo.type);
   data.append('file_attachment', fileToUpload);

   console.log("data.name is: "   data.name);  //"undefined"
   console.log("data.type is: "   data.type);  //"undefined"
   console.log("data.file_attachment is: "   data.file_attachment);  //"undefined"
   console.log("fileToUpload is: "   fileToUpload);  //correct

     //****UPLOAD TO SERVER

     fetch(`${SERVER_URL}/api/upload`, {
       method: 'POST',
       body: data,
       headers: { 'Content-Type': 'multipart/form-data' }
     })
     .then((response) => response.json())
     .then((response) => {
      console.log('Upload success: ', response);
      alert('Upload success!');
      this.setState({ photo: null });
     })
     .catch((error) => {
      this.setState({ photo: null });
      this.setState({ notify: "Pending Upload..." });
      console.log('Upload error: ', error);
      alert('Upload failed!');
     });

     //****

   } else {
   alert('Please Select File to Upload...');
   }  //'this.state.photo' is NOT NULL...OR NOT...

  };

...

}  //class 'Images' Component

As can be seen in my comments, the 'console.log' statements following the definition of the FormData and the '.append' statements are all "undefined" (in the 'UploadPhoto' function)...even the 'name' which was set to a simple string ('Image Upload') is not defined. So obviously the entire FormData command is totally non-functional.

I have spent days trying to figure this...difficult to believe in 2023 something like this should be so convoluted. I have previously had little difficulty uploading images from web applications before however this is my first attempt at using 'FormData' and attempting a file upload from React Native.

Any advice is greatly appreciated. I thank you in advance.

CodePudding user response:

To access values in FormData use get.

const data = new FormData();
data.append('name', 'Image Upload');
console.log("data.name is: "   data.get("name"));

To upload a file

const body = new FormData()
body.append('file', {uri: 'path/to/content', type: 'type', name: 'name'})
const response = await fetch('url', {
  method: 'POST',
  headers: {
    'Content-Type': 'multipart/form-data',
  },
  body: body
})
  • Related