1
votes

I've been dealing with this problem for a while now apparently you can upload a image using FormData and appending the file but I am still unable to get this to work. I have already tried with the following threads:

My first problem revolves around FormData().append(), in most solutions a blob/file is configured using the uri property but I don't have access to this property (Is this related to Typescript?). So something like this:

formData.append("profile_photo", {
     uri: values.imageURI
});

Here's the error TS is returning:

Argument of type '{ uri: string; }' is not assignable to parameter of type 'string | Blob'.
Object literal may only specify known properties, and 'uri' does not exist in type 'Blob'.ts(2345)

Another key points is setting up my axios client with the Content-Type header, I've done this during my POST request like so:

 // Perform a profile post request
const profileResponse = await loginClient.post(
      "/user_profile",
       formData,
       {
           headers: {
                "Content-Type": "multipart/form-data",
            },
       }
);

But by logging my request with Axios' interceptors, here how the request headers look like:

    headers:
    Accept: "application/json"
    Authorization: "Bearer 36|8SVw1DntRKni0sUn4NDX9moLluCHyYcZSadfgI5B"
    __proto__: Object

Just a few observations:

2
formData.append("profile_photo", values.imageURI); ? documentation - oops, nevermind, react-native may be different - sorryJaromanda X
values contains my submit form values, values.imageURI contains the image local uri.Jeremy
yes, it does - not sure how that relates to the type of data formData.append expects (string or blob I think the error states - you're passing an object) - try this SO questionJaromanda X

2 Answers

1
votes

Solved by using the Form-Data module, then you can easily pass in the uri like so:

formData.append("profile_photo", {
        uri: values.imageURI,
        name: "image.png",
        type: "image/png",
});

This could be improved by extracting the type from the uri tho.

0
votes

You need to send these 3 values while uploading a file.

  1. URI.
  2. Name.
  3. Type.

You can get all these values from the file picker. Send it as

const formData = new FormData();
formData.append("profile_photo", {
  uri: values.imageURI,
  name: values.name || "profile_photo.png",
  type: values.type || "image/png"
});

axios.post('upload_file', formData, {
    headers: {
      'Content-Type': 'multipart/form-data'
    }
});