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
42
43
44
45
// Function to upload data using Wormhole API and return the URL
async function uploadToFileIo(file) {
const formData = new FormData();
formData.append("file", file);
const response = await fetch("https://file.io", {
method: "POST",
body: formData,
});
const result = await response.json();
return result.link; // URL to the uploaded file
}
// Check if HTMLElement is defined to ensure the code runs in a browser environment
if (typeof HTMLElement !== "undefined") {
class UploadURL extends HTMLElement {
constructor() {
super();
this.fileInput = document.createElement("input");
this.fileInput.type = "file";
this.appendChild(this.fileInput);
this.urlInput = document.createElement("input");
this.urlInput.type = "hidden";
this.urlInput.name = this.getAttribute("name");
this.appendChild(this.urlInput);
}
connectedCallback() {
this.fileInput.addEventListener("change", async (event) => {
if (this.fileInput.files.length > 0) {
const file = this.fileInput.files[0];
console.log("Uploading...");
const url = await uploadToFileIo(file);
console.log(url);
this.urlInput.value = url; // Set the text input's value to the URL
// delete the file from the input
this.fileInput.files = null;
}
});
}
}
customElements.define("upload-url", UploadURL);
}
Val Town is a social website to write and deploy JavaScript.
Build APIs and schedule functions from your browser.
Comments
Nobody has commented on this val yet: be the first!
April 18, 2024