eunice_dai
eunice_dai

Reputation: 41

Error 500 Upload image to strapi with Axios

I need to upload image to Strapi. I have a table named book, and with three fields: b_type, b_num, b_image. However, the status code is 500, but without pushing b_image it is 200.

let file
    const ImageUpload = () =>{
        let box = document.querySelector('.popup_win')
        let uploadField = document.querySelector('.upload')
        uploadField.addEventListener('change', (e) =>{
            file = e.currentTarget.files[0]
            checkType(file)
        })
     }
const finish = ()=>{
        const form = new FormData()
        form.append('b_image', file)
        form.append('b_num', 3)
        form.append('b_type', 'student')

        axios.post('http://localhost:1337/books', form, {
            headers: {'Content-Type': 'multipart/form-data'}
        })
        .then((response) => {
            console.log(response.data)

        })
        .catch((e) => {
            console.log(e)
        })
        document.querySelector('.popup').style.display='none'
    }

Upvotes: 2

Views: 2582

Answers (2)

leto
leto

Reputation: 599

Took a while to work out but here's how I did it:

const submitUpload = e => {
  e.preventDefault();

  const formData = new FormData(e.target);

  axios.post("http://localhost:1337/images", {})
    .then(res => {
      console.log(res);

      formData.append('refId', res.data.id);

      axios.post(`http://localhost:1337/upload`, formData, {
        headers: { 'Content-Type': 'multipart/form-data' },
      })
        .then(res => {
          console.log(res);
        })
        .catch(err => {
          console.log(err);
        });
    })
    .catch(err => {
      console.log(err);
    });
}

return (
  <form id='form' onSubmit={e => submitUpload(e)}>
    <input type="file" name="files" />
    <input type="text" name="ref" value="image" />
    <input type="text" name="field" value="image" />
    <input type="submit" value="Submit" />
  </form>
)

The ref and refId input values' meanings are given here https://strapi.io/documentation/3.x.x/guides/upload.html#examples.

Upvotes: 1

Jim LAURIE
Jim LAURIE

Reputation: 4120

Here is the documentation about the file upload it can help you https://strapi.io/documentation/3.x.x/guides/upload.html#file-upload.

So first you have to create your Book entry without your image.

And then you have to upload your files and set the entry you want to link.

So it will be 2 request for that.

Here is an example https://strapi.io/documentation/3.x.x/guides/upload.html#examples We link an image to an existing article.

Upvotes: 1

Related Questions