Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
80 changes: 53 additions & 27 deletions docs/examples/drag-and-drop/script.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,40 +19,66 @@ 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/`;
}
console.log(`Hyper base URL: ${hyperdriveUrl}`);

// Perform the upload for each file
try {
const response = await fetch(url, {
method: 'PUT',
body: formData,
});
for (const file of files) {
const url = `${hyperdriveUrl}${encodeURIComponent(file.name)}`;
console.log(`Uploading ${file.name} to ${url}`);

if (!response.ok) {
addError(files, await response.text());
try {
const response = await fetch(url, {
method: 'PUT',
body: file, // Send raw file bytes
headers: {
'Content-Type': file.type || 'application/octet-stream'
}
});

console.log(`Response for ${file.name}: ${response.status}, ok: ${response.ok}`);
if (!response.ok) {
const errorText = await response.text();
console.error(`Error uploading ${file.name}: ${errorText}`);
addError(file.name, errorText);
continue;
}

addURL(url);
} catch (error) {
console.error(`Error uploading ${file.name}:`, error);
addError(file.name, error.message);
}
}
} else {
// Keep IPFS as FormData
const formData = new FormData();
for (const file of files) {
console.log(`Appending file for IPFS: ${file.name}`);
formData.append('file', file, file.name);
}
const url = `ipfs://bafyaabakaieac/`;
console.log(`Sending to IPFS: ${url}`);

try {
const response = await fetch(url, {
method: 'PUT',
body: formData,
});
console.log(`IPFS Response: ${response.status}`);
if (!response.ok) {
addError(files[0].name, await response.text());
return;
}
const locationHeader = response.headers.get('Location');
addURL(locationHeader);
} catch (error) {
console.error(`Error uploading to IPFS:`, error);
addError(files[0].name, error.message);
}
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' });
Expand All @@ -72,4 +98,4 @@ function addURL(url) {

function addError(name, text) {
uploadListBox.innerHTML += `<li class="log">Error in ${name}: ${text}</li>`
}
}