IHP 1.1 is out now!

Any way to upload files through API?

Lillo PRO

Hi!

I'm trying to attach a file to an IHP endpoint and catch that file with fileOrNothing, but nothing I try works. Tried everything from base64 to ArrayBuffer and File type in JS, but fileOrNothing ignores it.

I have primarily tried to do it with the FormData API, but there's just so many combinations of different web APIs to try that I think I'm giving up soon 😂

Also tried with and without setting multipart/form-data header etc.

marc PRO

I asume you're trying to send it via JS? If yes, check out the implementation of helpers.js

There it's also implemented using FormData

Lillo PRO

Thanks! That narrowed down what I am trying to do for sure!

Yes, it's through JS/React Native, but I need to use fetch in order to validate the response, but fetch also supports sending form data.

As I can deduce from logging the formData in helpers.js, it seems to definately be of a File type that is appended to the form.

Unfortunately it seems like the file is still getting ignored. I'm going to try to make a minimal reproducable example of this.

Lillo PRO

Doing it through JS/Web works fine, but I think something in React Native makes this very difficult to get right, so the files are definitely being filtered out by RN.

I can say for sure that it's not an issue with IHP for what it's worth.

marc PRO

I think back in 2018 react native had issues with file uploads in fetch. Back then we used XMLHttpRequest for these cases, because that for some reason supported file uploads. Maybe that issue is still not resolved and is the problem here?

Lillo PRO

I finally made it work!!

The big mistake I did was trying to work with a base64 image and try to encode this to some accepted format. Very complicated and inefficient!

But instead from the imagepicker/camera upload functionality in RN, there is is also a uri that points to the file in the native file system.

Appending an object like below with an URI was all it took. As usual the solution was extremely simple, I just looked in all the wrong places 😂

formData.append("productImage", {
        name: "file.png",
        uri: uri,
        type: "image/png"
      });
marc PRO

Perfect! :) That makes a lot of sense