react native post form data with object and file in it using axios
Asked Answered
S

5

17

enter image description here

so i want to upload object as data and file as Note to api using axios

uploadToServer= () => {
    const file =this.state.photo

  let data2 ={sale_id:1,
            note_type_id:4,
            description:"test",
            note_content_item:" hi from broker hub"
            
            }



let data = new FormData()
data.append('data[sale_id]', '1')
data.append('data[note_type_id]', '4')

data.append('data[description]', "test")

data.append('data[note_content_item]', "test")







console.log(data)


axios({
  url: api',
  method: 'POST',
  data: data,
  headers: {
   
            'Content-Type' : 'multipart/form-data',
          'Authorization':'Basic YnJva2VyOmJyb2tlcl8xMjM='

  }
})
        .then(resp => console.log(resp.data.response))
        .catch(error => console.error(error)); 

}

first i am trying with data without Note i can do it in postman

enter image description here

but with my code i got error

message: "Can not save file" response_code: 10

i got this error only if i change the key from data to something else enter image description here

Subcartilaginous answered 21/5, 2019 at 9:30 Comment(0)
H
21

You are not building FormData correctly, Try this:

let data = {sale_id:1,
                note_type_id:4,
                description:"test",
                note_content_item:" hi from broker hub"            
                }
const formData = new FormData();
formData.append('data', JSON.stringify(data));
formData.append('Note', {
                     uri: "file://" //Your Image File Path
                    type: 'image/jpeg', 
                    name: "imagename.jpg",
                  });
axios({
       url    : api,
       method : 'POST',
       data   : formData,
       headers: {
                    Accept: 'application/json',
                    'Content-Type': 'multipart/form-data',
                    'Authorization':'Basic YnJva2VyOmJyb2tlcl8xMjM='
                }
            })
            .then(function (response) {
                    console.log("response :", response);
           })
           .catch(function (error) {
                    console.log("error from image :");
           })
Hamburg answered 21/5, 2019 at 10:14 Comment(5)
Even I am following the same approach, but it's not working for me.Renelle
@bubble-cord what error/issue you getting, share your code so can understand your problem.Hamburg
I used same code but not working getting error from image : [Error: Network Error] , Kindly help, i already waste too much time, thank you in advanceProtero
Please add a note that FormData is from form-data package i.e. from import FormData from 'form-data' I was struggling to find what's the right one as the default FormData was pointing to VS Code app's internal one which is incorrect.Coelom
let updateModal = { Id: 1, CompanyName: this.state.companyName, }; const formData = new FormData(); formData.append('data', JSON.stringify(updateModal)); formData.append( 'CompanyLogo', // null, this.state.companyLOGO.uri this.state.companyLOGO.uri ); axios({ url: apiUrl, method: 'PUT', data: formData, headers: { Accept: 'application/json', 'Content-Type': 'multipart/form-data', Authorization: Bearer ${token}, }, }) }; getting server error 500Siward
N
31

when you are using react-native you don't need "form-data" package. Because react native polyfills standard FormData api and exports it as global.

second problem is axios converts form data automatically to string, so you need to use transformRequest config on request to override it.

import { AxiosRequestConfig } from "axios";
const FormData = global.FormData;

const axiosInstance = axios.create({
    baseURL: 'example.com', // use with scheme
    timeout: 30000,
    headers: {
        "X-Platform": 'iOS',
        "X-App-Build-Number": '1.0.0',
    },
});

const formData = new FormData();
formData.append("userId", "123456");
formData.append("file", {
    uri: "/dev/sda/abc.png",
    type: "image/png",
    name: "abc.png",
});

const config: AxiosRequestConfig = {
    method: "post",
    url: "/process/start",
    responseType: "json",
    headers: {
        'Content-Type': 'multipart/form-data',
        // if backend supports u can use gzip request encoding
        // "Content-Encoding": "gzip",
    },
    transformRequest: (data, headers) => {
        // !!! override data to return formData
        // since axios converts that to string
        return formData;
    },
    onUploadProgress: (progressEvent) => {
        // use upload data, since it's an upload progress
        // iOS: {"isTrusted": false, "lengthComputable": true, "loaded": 123, "total": 98902}
    },
    data: formData,
};

// send post request and get response
const response = await axiosInstance.request(config);
Neysa answered 14/2, 2022 at 18:45 Comment(6)
transformRequest was the key for me. It can even be transformRequest: (data) => { return data} and it worksSubarid
Thanks a lot. transformRequest was what was needed. I've been stuck with this for a while. Thanks againGerlach
Thank you so much, transformRequest fixed it! Interestingly, for me the requests broke after upgrading axios from 0.24.0 to 0.26.0. Before this, I was sending form data without transformRequest and it was working just fine ¯_(ツ)_/¯Garett
It seems the following PR introduces the breaking change affecting react-native: github.com/axios/axios/pull/3757#issuecomment-1081931773Garett
Saved my day! The transformRequest option did the fix.Anthodium
Super helpful! Thank you so much! Could you link some sources where we could find more info about how "react native polyfills standard FormData api and exports it as global"Multiple
H
21

You are not building FormData correctly, Try this:

let data = {sale_id:1,
                note_type_id:4,
                description:"test",
                note_content_item:" hi from broker hub"            
                }
const formData = new FormData();
formData.append('data', JSON.stringify(data));
formData.append('Note', {
                     uri: "file://" //Your Image File Path
                    type: 'image/jpeg', 
                    name: "imagename.jpg",
                  });
axios({
       url    : api,
       method : 'POST',
       data   : formData,
       headers: {
                    Accept: 'application/json',
                    'Content-Type': 'multipart/form-data',
                    'Authorization':'Basic YnJva2VyOmJyb2tlcl8xMjM='
                }
            })
            .then(function (response) {
                    console.log("response :", response);
           })
           .catch(function (error) {
                    console.log("error from image :");
           })
Hamburg answered 21/5, 2019 at 10:14 Comment(5)
Even I am following the same approach, but it's not working for me.Renelle
@bubble-cord what error/issue you getting, share your code so can understand your problem.Hamburg
I used same code but not working getting error from image : [Error: Network Error] , Kindly help, i already waste too much time, thank you in advanceProtero
Please add a note that FormData is from form-data package i.e. from import FormData from 'form-data' I was struggling to find what's the right one as the default FormData was pointing to VS Code app's internal one which is incorrect.Coelom
let updateModal = { Id: 1, CompanyName: this.state.companyName, }; const formData = new FormData(); formData.append('data', JSON.stringify(updateModal)); formData.append( 'CompanyLogo', // null, this.state.companyLOGO.uri this.state.companyLOGO.uri ); axios({ url: apiUrl, method: 'PUT', data: formData, headers: { Accept: 'application/json', 'Content-Type': 'multipart/form-data', Authorization: Bearer ${token}, }, }) }; getting server error 500Siward
H
0

formData.append("file", { uri: //file.uri, type:"multipart/form-data", // type must be multipart/form-data name: file.name, });

Horsewhip answered 7/6, 2023 at 12:38 Comment(1)
Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.Robillard
K
0

When we upload image on react native web its return below error Error : Multipart: unexpected end of form, status: 400

Solution

I have Fixed this issue, Please see the below attached code for solution

const uploadOnWeb = async(uri: string) => {
    const filename = $ {
      Date.now()
    }.png;
    const formData = new FormData();
    const base64Image = uri.replace(/^data:image/\
      w + ; base64, /, '');
      const binary = atob(base64Image);
      const array = [];
      for (let i = 0; i < binary.length; i++) {
        array.push(binary.charCodeAt(i));
      }
      const file = new Blob([new Uint8Array(array)], {
        type: 'image/png'
      }); formData.append('file', file, filename);
      try {
        const token = await Storage.getItem('authToken');
        const response = await fetch($ {
            REACT_APP_API_URL
          }
          /upload/$ {
            filename
          }, {
            method: 'POST',
            headers: {
              Authorization: Bearer $ {
                token
              },
            },
            body: formData,
          });
        if (response.status === 201) {
          alert('Image uploaded successfully');
        } else {
          alert('There is some error uploading image');
        }
      } catch (error) {
        alert('There is some error uploading image');
      }
    };
Kevinkevina answered 17/6, 2024 at 7:17 Comment(0)
R
-1

This might help you:

import {Platform} from 'react-native';
import axios from 'axios';

    const upload = async readPath => {
    console.log('path', readPath);
    const URL = 'your-url';
    const headers = {
      headers: {
        'Content-Type': 'multipart/form-data',
        Accept: 'application/json',
        Authorization: `Bearer ${projectSecret}`,
      },
    };
    const formData = new FormData();
    const file = {
      uri:
        Platform.OS === 'android' ? `file:///${readPath}` : readPath,
      type: 'text/plain',
      name: name,
    };
    formData.append('file', file);

    await axios
      .post(URL, formData, headers, {
        timeout: 3000,
      })
      .then(async response => {
        console.log(response.data);
      })
      .catch(error => {
        console.log('error : ', error);
      });
  };
Rapscallion answered 27/12, 2022 at 16:17 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.