How to upload image to content collection

Strapi 3
I"m obviously doing something wrong here but can’t figure it out :frowning:
My model:

  "attributes": {
    "HTML": {
      "collection": "file",
      "via": "related",
      "allowedTypes": [
        "files",
        "images",
        "videos"
      ],
      "plugin": "upload",
      "required": false
    },
    "CustomFields": {
      "type": "json"
    }
  }

I make the axios call and set up like so:

  const fileContent = fs.readFileSync(destFile, { encoding: 'base64' });
  console.log(fileContent);
  let bodyData = new FormData();
  bodyData.append('HTML', fileContent);


  axios.post(`http://myip/templates`, bodyData, {
          headers: {
          'Authorization': `Bearer ${jwtResp.data.jwt}` },

        })

    .then(response => console.log(JSON.stringify(response.data)) )
    .catch(error => console.log(error.data) )

It creates a record din templates but no data gets added.
I’ve tried

  bodyData.append('file', fileContent);
  bodyData.append('files', fileContent);

None works the data isn’t getting passed. Again it creates a record but with no data. Any idea what I’m doing wrong? I’m sure it’s something on my end.

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

Hi thanks for submitting this.
const postImageResponse = await axios.post('[your-base-url]/images');
Is this route a collection or model you set? Or is that a native strapi route? I get a 405 when try to hit that.

It’s a content-type/collection. I don’t believe you need to create it; the important part is retrieving the image field id that the upload will be related to before uploading.