What is the method for adding local images to FormData in Expo version 48 and above?

When working with Expo v47 and its corresponding React Native and TypeScript versions, FormData.append had the following typing:

FormData.append(name: string, value: any): void

An example of appending images using this code could be:

const image = {
  uri: x.uri,
  name: x.name,
  size: x.size,
  type: 'image/jpeg',
}

const formDataBody = new FormData()
formDataBody.append('data', image)

However, in Expo v48 and v49, along with their matching RN and TS versions, the typing has now changed to:

FormData.append(name: string, value: string | Blob): void

I attempted to adapt my code to match the new typing, but I encountered a Network Error when trying to POST the FormData:

try {
  base64String = await FileSystem.readAsStringAsync(image.uri, { encoding: 'base64' })
} catch (error: any) {
  // ...
}

const binaryData = decode(base64String)

//create a Uint8Array to represent the binary data
const buffer = new Uint8Array(binaryData.length)
for (let i = 0; i < binaryData.length; i++) {
  buffer[i] = binaryData.charCodeAt(i)
}

//create a File object from the binary data
const file = new File([binaryData], 'data', { type: 'image/jpeg' })

formDataBody.append('data', file)

I am also aware that modules like react-native-fs can be utilized, but I encountered an error message:

ERROR  Invariant Violation: "main" has not been registered. This can happen if:
Metro (the local dev server) is run from the wrong folder. Check if Metro is running, stop it and restart it in the current project.
A module failed to load due to an error and `AppRegistry.registerComponent` wasn't called., js engine: hermes

Any assistance or guidance on this matter would be greatly appreciated!

Answer №1

Personally, I found the solution by doing the following:

import FormData from "form-data";

//...

const formData = new FormData();

formData.append('photo', {
  uri: photoURL,
  name: picName,
  fileType
});

I'm currently using Expo SDK version 52 and in my scenario, form-data was already included as a dependency of @expo/cli. However, you might need to install the library separately based on your setup.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How to access the result without using subscribe in Angular?

I am facing unexpected behavior with a method in my component: private fetchExternalStyleSheet(outerHTML: string): string[] { let externalStyleSheetText: string; let match: RegExpExecArray; const matchedHrefs = []; while (match = this.hrefReg.exe ...

Unlock the power of Env variables on both server and client components with Next.js! Learn how to seamlessly integrate these

In my Next.js app directory, I am facing the need to send emails using Nodemailer, which requires server-side components due to restrictions on client-side sending. Additionally, I am utilizing TypeScript in this project and encountering challenges when tr ...

Sending various data from dialog box in Angular 8

I have implemented a Material Design dialog using Angular. The initial example had only one field connected to a single parameter in the parent view. I am now trying to create a more complex dialog that collects multiple parameters and sends them back to t ...

Trouble arises in AWS Code Pipeline as a roadblock is encountered with the Module

After many successful builds of my Angular project, it suddenly fails to build on AWS Code Build. I reverted back to a commit before any recent changes, but the error persists. When I run ng build --prod locally, it works fine. However, during the pipeline ...

Creating an expo apk using eas buildWould you like a tool for generating

Following an update to Expo, the process of building apk files using expo build:android -t apk is no longer supported. Instead, it now recommends using eas builds with the command eas build -p android --profile preview. However, this resulted in building a ...

What is the best way to handle node module dependencies when you have made custom code modifications within the dependencies?

Currently, I am in the midst of developing a react-native mobile application for both Android and iOS. A certain issue has arisen where I needed to make modifications to a NavigationReactGateway.java file located within the node_modules/react-native-naviga ...

Tips for converting a date string to a date object and then back to a string in the same format

I seem to be encountering an issue with dates (shocker!), and I could really use some assistance. Allow me to outline the steps I have been taking. Side note: The "datepipe" mentioned here is actually the DatePipe library from Angular. var date = new Dat ...

Is it possible to assign a property value to an object based on the type of another property?

In this illustrative example: enum Methods { X = 'X', Y = 'Y' } type MethodProperties = { [Methods.X]: { x: string } [Methods.Y]: { y: string } } type Approach = { [method in keyof Method ...

Generating instances of classes using variables in Typescript

Are there methods to modify the below piece of code in order for it to be compatible with Typescript? public shops: string[] = [ "AShop", "BShop", "CShop", ]; this.shops.forEach((shop, index) => { let instance = new window[shop](index ...

Guide on retrieving a nested JSON array to extract a comprehensive list of values from every parameter within every object

A JSON file with various data points is available: { "success": true, "dataPoints": [{ "count_id": 4, "avg_temperature": 2817, "startTime": "00:00:00", "endTime": "00:19:59.999" }, ... I am trying to extract all the values of & ...

What are the steps to resolve the error message "Make sure the component is enclosed within a <Provider>" while using Next 14 with Redux Toolkit?

I've been struggling to get Next.js 14 to work with Redux Provider. I followed all the guidelines on the Redux official documentation here, but I keep encountering this error: Error: could not find react-redux context value; please ensure the compo ...

What is the best way to launch the Playwright browser in Jest using the setupFilesAfterEnv hook, to ensure accessibility within the test file while incorporating TypeScript?

When using Jest and Playwright, I encountered an issue where I wanted to launch the browser from setupFilesAfterEnv in order to avoid repeating the process in every test file. Despite successfully launching the browser and having global variables accessibl ...

What is the best way to enhance a React Native component's properties with Flow?

I'm currently working with Flow version 0.54.1 in my React Native project, specifically using version 0.48.3. I have developed a component named PrimaryButton that acts as a wrapper for the native TouchableOpacity component. My goal is to define custo ...

There was an error in the CSS syntax in the production environment due to a missed semicolon

Trying to execute the npm build command "webpack --mode=production --config ./config/webpack.config.prod.js" on our project results in an issue. The issue arises when I include the bootstrap file in my tsx file as shown below. import bs from "../../../../ ...

In order to activate the input switch in Next.Js, it is necessary to initiate a

Currently, I am working on implementing an on-off switch in Next.Js. To seek assistance, I referred to this helpful video tutorial: https://www.youtube.com/watch?v=1W3mAtAT7os&t=740s However, a recurring issue I face is that whenever the page reloads, ...

Retrieving the attribute key from a dynamically typed object

Having this specific interface structure: interface test { [key: string]: string } along with an object defined as follows: const obj: test ={ name: 'mda', telephone: '1234' } Attempting to utilize this object in a variab ...

Transitioning from Angular Http to HttpClient: Overcoming Conversion Challenges

Currently, I am in the process of converting my old Angular app from Http to HttpClient. While working on the service.ts section, I encountered an error that I am struggling to resolve: ERROR Error: Cannot find a differ supporting object '[object Ob ...

Issues arising with code splitting using React HashRouter in a project utilizing Typescript, React 17, and Webpack 5

Encountered build issues while setting up a new project with additional dependencies. package.json: { "name": "my-files", "version": "1.0.0", "description": "App", "main": " ...

Launching a new tab with a specific URL using React

I'm attempting to create a function that opens a new tab with the URL stored in item.url. The issue is, the item.url property is provided by the client, not by me. Therefore, I can't guarantee whether it begins with https:// or http://. For insta ...

Arranging an array of integers followed by sorting by the decimal part of each value in a particular sequence using JavaScript

Below is an example of sorting an array: let arr = ['100.12', '100.8', '100.11', '100.9']; When sorted traditionally, the output is: '100.11', '100.12', '100.8', '100.9' Ho ...