The React Native blob or file seems to be encountering trouble in reaching the server

I'm in a tough spot here. I can't figure out what's going wrong. My goal is to send a file using the expo-image-picker component to the server. The form gets sent, but the image doesn't. When I use the fetch command, I immediately get a "Network request failed" error. The server receives the request, but without the image attached.

Additional details:

  • I've tried creating a form-data object and appending the blob to it. I also attempted using

    FormData.append("image", {uri, name: 'filename', type: 'image/filetype'})
    as suggested in many articles, ignoring the TypeScript error, but it failed too.

  • I'm not utilizing AWS or Firebase, so I'm not using those libraries. I don't see a significant difference in how they handle it compared to my approach.

  • I haven't defined any specific permissions for this process. I came across some discussions about permissions for uploads, but the information seemed outdated, referencing times before Android 5.0.

Below are the functions I'm using for the submission, with pathToImage being returned from the ImagePicker.

const fetchImageFromUri = async (uri: string) => {
  try {
    const response = await fetch(uri);
    const blob = await response.blob();

    return blob;
  } catch (error) {
    console.log("fetchImageFromUri error:", error);
    throw new Error("fetchImageFromUri");
  }
};

const upload = async () => {
  setMessage("");
  setErrMessage("");

  if (pathToImage != null) {
    const fileToUpload = await fetchImageFromUri(pathToImage);

    const formData = new FormData();
    formData.append("action", "Image Upload");
    formData.append("image", fileToUpload, "filename");

    // Rest of the upload function goes here

You can access the complete code in my GitHub repository.

Answer №1

I want to extend my gratitude to Brandonjgs for guiding me in the right direction. Thanks to his help, I was able to successfully tackle the issue at hand.

Below is the updated upload function.

const upload = async () => {
    console.log("\n***** Upload Image *****");
    setMessage("");
    setErrMessage("");
    setLoading(true);

    if (pathToImage) {
        console.log("***** get other fields section *****");
        const dataToSend: Record<string, string> = {};
        dataToSend["action"] = "Image Upload";

        console.log("***** Options section *****");
        const options: FileSystemUploadOptions = {
            headers: {
                "Content-Type": "multipart/form-data",
                Accept: "image/jpeg, image/png",
            },
            httpMethod: "POST",
            uploadType: FileSystemUploadType.MULTIPART,
            fieldName: "image",
            parameters: dataToSend,
        };

        console.log("***** 'Fetch' section *****");
        try {
            const response = await FileSystem.uploadAsync(
                URL,
                pathToImage,
                options
            );

            setLoading(false);

            if (response.status >= 200 && response.status < 300) {
                const body = JSON.parse(response.body);
                setMessage(body.msg);
            } else {
                setErrMessage(`${response.status} Error: ${response.body}`);
            }
        } catch (err: any) {
            console.error(err);
            setErrMessage(err.message);
        }
    }
};

Make sure to refer to the FileSystem.uploadAsync documentation for more insights. It does not return a standard http response; instead, it formats its own and returns:

  • status: the error code
  • header: the http header sent by the server
  • body: the data returned by the server - in my case, it's JSON. It's worth noting that if the server is unresponsive or the URL is incorrect, it returns an HTML error page rather than a standard error message string (which can be unconventional since this is a react native environment and not necessarily a web page redirection scenario).

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

Saving large amounts of data in bulk to PostgreSQL using TypeORM

I am looking to perform a bulk insert/update using TypeORM The Test entity is defined below: export class Test { @PrimaryColumn('integer') id: number; @Column('varchar', { length: 255 }) testName: string; } I have the f ...

NestJs encountering issues with reading environment variables

I used the instructions from the Nest documentation to set up the configuration, however, it's not functioning correctly. app.module.ts @Module({ imports: [ ConfigModule.forRoot({ isGlobal: true }), TypeOrmModule.forRoot(config), AuthMo ...

Is there a way to establish a "transient" category within a category to maintain code efficiency?

I'm struggling to figure out how to search for this specific question on Stack Overflow. The structure of my generic type FetchOptions looks like this: type FetchOptions<T> = { explode?: string & keyof T | (string & keyof T)[]; } I&a ...

Utilizing Typescript with tfjs-node to effectively integrate the node-gpu version with regular node functionalities

I am facing challenges while running my Tensorflow.js node application with and without the GPU library. In vanilla JavaScript, examples show using require() for either @tensorflow/tfjs-node or @tensorflow/tfjs-node-gpu. However, in my TypeScript setup, I ...

Encountering issues while attempting to import Realm in my project. Error message says: "Missing Realm constructor. Have you executed 'pod install'? (Working on a Windows machine)"

I've been working on a mobile app project using React Native and I wanted to integrate Realm (MongoDB) into it. After running: npm install realm I noticed that Realm was successfully added in the "node_modules" folder. When I tried to import Realm wi ...

Typescript - The Power of Dynamic Typing

Currently, I am attempting to demonstrate this example => typescript playground const obj = { func1: ({ a }: { a: string }) => { console.log(a) }, func2: ({ b }: { b: number }) => { console.log(b) }, } function execFunction<Key extends ...

Utilizing React MUI Autocomplete to Save Selected Items

Exploring the realms of React and TypeScript, I find myself puzzled by a task at hand. It involves storing user-selected options from an Autocomplete component and subsequently sending these values to an external API. Is there a recommended approach for ac ...

The StreamingTextResponse feature is malfunctioning in the live environment

When I share my code, it's an API route in Next.js. In development mode, everything works as expected. However, in production, the response appears to be static instead of dynamic. It seems like only one part of the data is being sent. I'm puzzl ...

The error message "TypeError: 'results.length' is not an object" occurred within the Search Component during evaluation

Having trouble with a search feature that is supposed to display results from /api/nextSearch.tsx. However, whenever I input a query into the search box, I keep getting the error message TypeError: undefined is not an object (evaluating 'results.lengt ...

Achieving dynamic key assignment when updating with mongoose in NodeJS and Express

With a multitude of keys requiring updates from a single function, I am seeking guidance on how to dynamically set the key for updating. static async updateProfile(req, res, next) { const userId = req.body.userId; // The key requiring an update ...

Populating the DOM with a mix of strings and HTMLDivElements by iterating through an array using *ngFor

I have a specific layout requirement that needs to resemble this example: https://i.sstatic.net/4kP2q.png The desired layout should utilize CSS properties like display: grid; someFunction(data) { this.data = data; ...

Tips for making use of incomplete types

Is there a way to reference a type in TypeScript without including all of its required fields, without creating a new interface or making all fields optional? Consider the following scenario: interface Test { one: string; two: string; } _.findWhe ...

Tips for typing a narrow JSX.Element

Is there a way to create a variable in React that can be either a component or a string? Like this: function MyComponent(): JSX.Element { let icon: JSX.Element | string = "/example.png"; return <div>{typeof icon === "JSX.Element" ? icon : <i ...

Accessing JSON files within React Native applications

I'm struggling to read a JSON file from my directory and save its data in a useState variable. I have tried numerous methods and searched extensively for solutions without success. mydata.json: { "key":"value" } My code : ...

Expo background fetch initialized but not activated

During the development of my React Native app, I encountered the need to perform periodic background fetches from another server. To achieve this, I utilized two classes from Expo: import * as BackgroundFetch from 'expo-background-fetch'; import ...

Searching for TypeScript type definitions for the @Angular libraries within Angular 2

After updating my application to Angular2 v2.0.0-rc.1, I am encountering TypeScript compile errors and warnings when webpack bundles my application. These messages appear for any @angular packages referenced in my TypeScript source files: ERROR in ./src/a ...

Unable to fulfill the pledge

I'm struggling to receive the promise from the backend after making a get request. Can anyone help me figure out what I might be doing wrong? makeLoginCall(_username: string, _password: string) { let promise = new Promise((resolve, reject) => ...

ng-select search functionality failing to display any matches

Currently, I am encountering an issue with the ng-select functionality in my Angular CLI version 11.2.8 project. Despite using ng-select version 7.3 and ensuring compatibility with the Angular CLI version, the search functionality within the select eleme ...

What is the best way to implement an onClick event listener in a TypeScript React application?

Is there a way to properly add an onClick event listener to a div element in my code snippet below? useEffect(() => { if (ref.current === null) { return; } const handleClick = (el: HTMLDivElement, e: MouseEvent) = ...

Angular2: Ways to update components with resolver dependencies?

In my project, I have three separate components, each with its own resolver that retrieves data from distinct APIs. These components all depend on a shared URL provided by a service. My goal is to ensure that when the URL changes, each component refreshes ...