#Refactoring Code for FormData Post Request

9 messages · Page 1 of 1 (latest)

storm runeBOT
#

Hello,

I need assistance in modifying the code to send a POST request using FormData for uploading photos to the server. I have the following function:

const _upload = async (file, name, caption, alternativeText) => {
  try {
    const data = {
      fileInfo: JSON.stringify({
        alternativeText,
        caption,
        name,
      }),
      files: { file, content_type: mime.lookup(file) },
    };
    const { body } = await needle("post", strapiUrl + "/api/media", data, {
      multipart: true,
      headers: {
        authorization: _axios.defaults.headers.Authorization,
      },
    });
    return Array.isArray(body) ? (body.length > 0 ? body[0] : null) : body;
  } catch (e) {
    console.error(`File upload error: ${e.message}`);
    return null;
  }
};

I want to refactor this function to use FormData for sending the POST request. How can I do this correctly? Thank you!

unique crowBOT
#

Original message from @bleak kite - Moved from #general message

#
candid heron
#

Morning @bleak kite

#

Are you setting the correct header?
'Content-Type': 'multipart/form-data'

bleak kite
#

yes, but that doesn't solve the problem

const _upload = async (file, name, caption, alternativeText) => {
  try {
    const formData = new FormData();
    formData.append('file', file);
    formData.append('data', JSON.stringify({
      alternativeText,
      caption,
      name,
    }));

    const response = await fetch(payloadUrl + "/api/media", {
      method: "POST",
      headers: {
"Content-Type": "multipart/form-data"
        authorization: _axios.defaults.headers.Authorization,
      },
      body: formData,
    });

    const body = await response.json();
    return body;
  } catch (e) {
    console.error(`File upload error: ${e.message}`);
    return null;
  }
};
candid heron
#

What the error you get?

#

Is there access control set on the collection?