1

how to upload image to api using axios

i want to upload image with data to api using axios i try with formdata but it did not work see below my code

how it work in postman

and this is my code

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



let formdata = new FormData()
formdata.append('sale_id', 1)
formdata.append('note_type_id', 4)

formdata.append('description', "test")

formdata.append('note_content_item', "test")

formdata.append('Note', file)


   axios.post('api',
        {data:formdata},{headers: {
          'Content-Type' : 'multipart/form-data',
          'Authorization':'xx'
            }

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

}

i try a lot of solution but it give me Error: Request failed with status code 500

Firas Abu Fares
  • 511
  • 1
  • 6
  • 24
  • Spelling error on 'Content-type' inside axios request. Change that and try again? – Mick Vader May 20 '19 at 12:38
  • thank you @MickVader now i got error code 500?? – Firas Abu Fares May 20 '19 at 13:50
  • Do you own the server or have access to it? If so the server side stack trace of when your request pings could help narrow it down. I would guess it has something got to do with your formdata object though if postman is successful.. [EDIT] try adding formdata straight into the params of the axios.post request: `axios.post('api', formdata, {headers:...);` – Mick Vader May 20 '19 at 14:03
  • axios.post('api', formdata, {headers:...); now i have access but i got this response { "response": { "message": "Can not save file", "response_code": 10 } } in the postman i got this response if i change the KEY data to something else – Firas Abu Fares May 20 '19 at 15:28
  • so i change the key from formdata to data let data = new FormData() data.append('sale_id', '1') data.append('note_type_id', '4') data.append('description', "test") data.append('note_content_item', "test") axios.post('api',data ,{headers: { but still got the same thing can not save file – Firas Abu Fares May 20 '19 at 15:30
  • Please try this out. It helped me : https://stackoverflow.com/a/64161651/8013132 – ABM Apr 06 '21 at 12:03

1 Answers1

2

The 500 Internal Server Error is a very general HTTP status code that means something has gone wrong on the server. You can request like this (using fetch):

let formdata = new FormData()

formdata.append('description', "test")

let i = {
    uri: image.path,
    type: 'multipart/form-data',
    name: `image.jpg`,
};
formdata.append('image', i);

fetch(YourApi,{
    method: 'post',
    headers: {
        'Content-Type': 'multipart/form-data',
    },
        body: formdata
}).then(response => {
    response.text().then((res)=>{
        console.warn(res)
    })
}).catch(err => {
    console.warn('error')
})
Milad Jafari
  • 1,135
  • 1
  • 11
  • 28