Upload image using v2 Media endpoint from Javascript
Hello,
The project I am currently working is for a mobile react native app that will use the v2 APIs to create new discussions. I want to be able to upload images using a API v2 /media POST. All the documentation says is that we only need to pass "file": "string". However the code is looking for an instance of a PHP class UploadedFile.
Is there a way to use the /media endpoint to upload an image without using PHP?
Thanks
0
Comments
The endpoint needs an actual file passed to. This is our utilization of in from our javascript frontend:
https://github.com/vanilla/vanilla/blob/master/library/src/scripts/apiv2.ts
/** * Upload an image using Vanilla's API v2. * * @param file - The file to upload. */ export async function uploadFile(file: File, requestConfig: AxiosRequestConfig = {}) { const allowedAttachments = getMeta("upload.allowedExtensions", []) as string[]; const maxSize = getMeta("upload.maxSize", 0); const filePieces = file.name.split("."); const extension = filePieces[filePieces.length - 1] || ""; if (file.size > maxSize) { const humanSize = humanFileSize(maxSize); const stringTotal: string = humanSize.amount + humanSize.unitAbbr; const message = sprintf(t("The uploaded file was too big (max %s)."), stringTotal); throw new Error(message); } else if (!allowedAttachments.includes(extension)) { const attachmentsString = allowedAttachments.join(", "); const message = sprintf( t( "The uploaded file did not have an allowed extension. \nOnly the following extensions are allowed. \n%s.", ), attachmentsString, ); throw new Error(message); } const data = new FormData(); data.append("file", file, file.name); const result = await apiv2.post("/media", data, requestConfig); return result.data; }