How to upload image to content collection

I don’t quite understand what you’ve tried to do above as I’m a bit of a newb but below is my solution that hopefully helps

Uploads need to be posted to the upload endpoint (see docs). I believe you need to create the entry with an Image field your upload will be related to first and then post the upload with the image field id appended as ‘refId’ to the formdata.

I did it like so:

JSX

<form
  id="upload-form"
  onSubmit={handleUploadFormSubmit}
>
  <input
    type="file"
    name="files"
   />
</form>

JS

async function handleUploadFormSubmit(e) {
  e.preventDefault();
  const formData = new FormData(e.target);
  formData.append('ref', 'image');
  formData.append('field', 'image');

  try {
    const postImageResponse = await axios.post('[your-base-url]/images'); // creating an image content-type seems a good solution
    const newImageId = postImageResponse.data.id;
    formData.append('refId', newImageId);
    const uploadHeaders = {'Content-Type': 'multippart/form-data'}
    axios.post('[your-base-url]/upload', formData, {headers: uploadHeaders});
  }
3 Likes