Readme

uploadImage

uploads an image to val.town just like when you paste an image into a readme

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
/**
* upload an image to val.town
* @param {Blob} image - image must have image/jpeg, image/png, image/webp, image/gif or image/svg+xml content-type
* @returns {string} - uploaded image url
*/
export async function uploadImage(image: Blob): Promise<string> {
const fd = new FormData();
fd.append(
"file",
image,
);
const data = await (await fetch(await getUploadURL(), {
"body": fd,
"method": "POST",
})).json();
if (!data.success) {
if (data.errors?.length) {
throw new Error(data.errors.map(e => e.message).join("\n"));
} else {
throw new Error(JSON.stringify(data));
}
}
return data.result.variants[0];
}
async function getUploadURL(): Promise<string> {
const data = await (await fetch("https://www.val.town/api/trpc/generateImageUploadUrl", {
"headers": {
"content-type": "application/json",
"authorization": "Bearer " + Deno.env.get("valtown"),
},
})).json();
if (data?.result?.data?.success && data?.result?.data?.result?.uploadURL) {
return data.result.data.result.uploadURL;
} else {
if (data?.result?.data?.errors?.length) {
throw new Error(data.result.data.errors.map(e => e.message).join("\n"));
} else {
throw new Error(JSON.stringify(data));
}
}
}
Val Town is a social website to write and deploy JavaScript.
Build APIs and schedule functions from your browser.
v10
May 21, 2024