This code snippet demonstrates a JavaScript fetch
request that sends a PUT request to a dynamic API endpoint. Below is a concise documentation for the request:
- Endpoint: The target API endpoint is
https://cooptheapp.spikeysanju.workers.dev/
, which seems to be hosted on Cloudflare Workers. - When uploading a file set filename and it's extenstion as endpoint. ex - https://cooptheapp.spikeysanju.workers.dev/sanju.png (you can give any random names but make sure to provide extension)
-
HTTP Method: PUT
- The
fetch
function is configured to send a PUT request to the specified endpoint.
- The
-
Headers:
- Content-Type: The
Content-Type
header is set dynamically based on thefileType
variable. It indicates the media type of the file being transmitted. Examples includeimage/png
,image/jpeg
,image/gif
, andvideo/mp4
. The format offileType
is expected to be in the form of.png
,.jpeg
,.gif
, or.mp4
. - X-CF-Secret: This custom header,
X-CF-Secret
, is possibly used for authentication purposes.
- Content-Type: The
-
Request Body:
- The body of the request is constructed using a Uint8Array converted from binary data. It appears to handle the conversion of base64-encoded data to binary. The base64 data is extracted from the
file
variable, removing any data URI prefix (data:image/png;base64,
).
- The body of the request is constructed using a Uint8Array converted from binary data. It appears to handle the conversion of base64-encoded data to binary. The base64 data is extracted from the
-
Response Handling:
- The response is logged to the console assuming it is in text format. If the response is not in text format, consider using appropriate methods to handle different content types.
const apiEndpoint = 'https://cooptheapp.spikeysanju.workers.dev/sanju.png';
const fileType = 'image/png'; // Replace with the actual file type. Ex file type : image/png or image/jpeg or image/gif or video/mp4
const CLOUDFLARE_SECRET = 'your-secret'; // Replace with the actual Cloudflare secret
const file = 'base64_encoded_data_here'; // Replace with the actual base64-encoded data
const response = await fetch(apiEndpoint, {
method: 'PUT',
headers: {
'Content-Type': fileType,
'X-CF-Secret': CLOUDFLARE_SECRET
},
body: Uint8Array.from(atob(file.replace(/^data[^,]+,/, '')), (v) => v.charCodeAt(0))
});
console.log(await response.text());
- Ensure that placeholders like
fileType
,CLOUDFLARE_SECRET
, andfile
are replaced with actual values. - Verify the API documentation for additional details on authentication, expected responses, and any specific requirements.
@msomu please check this out!