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

6
  • Spelling error on 'Content-type' inside axios request. Change that and try again? Commented May 20, 2019 at 12:38
  • thank you @MickVader now i got error code 500?? Commented May 20, 2019 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:...); Commented May 20, 2019 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 Commented May 20, 2019 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 Commented May 20, 2019 at 15:30

1 Answer 1

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')
})
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.