-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathscript.js
75 lines (61 loc) · 1.99 KB
/
script.js
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
function $(query) {
return document.querySelector(query)
}
const uploadBox = $('#uploadBox')
uploadBox.ondragover = () => false
uploadBox.ondrop = async (e) => {
e.preventDefault()
const { dataTransfer } = e
if(!dataTransfer) return
await uploadFiles(dataTransfer.files);
}
const uploadListBox = $('#uploadListBox')
const protocolSelect = $('#protocolSelect')
async function uploadFiles(files) {
const protocol = protocolSelect.value;
const formData = new FormData();
// Append each file to the FormData
for (const file of files) {
formData.append('file', file, file.name);
}
// Construct the URL based on the protocol
let url;
if (protocol === 'hyper') {
const hyperdriveUrl = await generateHyperdriveKey('drag-and-drop');
url = `${hyperdriveUrl}`;
} else {
url = `ipfs://bafyaabakaieac/`;
}
// Perform the upload for each file
try {
const response = await fetch(url, {
method: 'PUT',
body: formData,
});
if (!response.ok) {
addError(files, await response.text());
}
const urlResponse = protocol === 'hyper' ? response.url : response.headers.get('Location');
addURL(urlResponse);
} catch (error) {
console.error(`Error uploading ${files}:`, error);
}
}
async function generateHyperdriveKey(name) {
try {
const response = await fetch(`hyper://localhost/?key=${name}`, { method: 'POST' });
if (!response.ok) {
throw new Error(`Failed to generate Hyperdrive key: ${response.statusText}`);
}
return await response.text(); // This returns the hyper:// URL
} catch (error) {
console.error('Error generating Hyperdrive key:', error);
throw error;
}
}
function addURL(url) {
uploadListBox.innerHTML += `<li><a href="${url}">${url}</a></li>`
}
function addError(name, text) {
uploadListBox.innerHTML += `<li class="log">Error in ${name}: ${text}</li>`
}