Skip to content

Commit

Permalink
Add support for resumable downloads in app.js
Browse files Browse the repository at this point in the history
  • Loading branch information
shhossain committed Dec 16, 2023
1 parent 1478fc0 commit 5684598
Showing 1 changed file with 42 additions and 4 deletions.
46 changes: 42 additions & 4 deletions app.js
Original file line number Diff line number Diff line change
Expand Up @@ -122,14 +122,52 @@ module.exports = ({ sharedPath: sharedPathIn, port, maxUploadSize, zipCompressio
if (isDir) {
await serveDirZip(filePath, res);
} else {
if (forceDownload) {
// NOTE: Must support non latin characters
try {
const stat = await fs.stat(filePath);
const fileSize = stat.size;

// if (forceDownload) {
// // Set the filename in the Content-disposition header
// res.set('Content-disposition', contentDisposition(basename(filePath)));
// }

res.set('Content-disposition', contentDisposition(basename(filePath)));
}

await pipeline(fs.createReadStream(filePath), res);
// Check if the client supports resumable downloads
const range = req.headers.range;
if (range) {
const parts = range.replace(/bytes=/, '').split('-');
const start = parseInt(parts[0], 10);
const end = parts[1] ? parseInt(parts[1], 10) : fileSize - 1;
const chunkSize = (end - start) + 1;

// Set headers for resumable download
res.status(206).set({
'Content-Range': `bytes ${start}-${end}/${fileSize}`,
'Accept-Ranges': 'bytes',
'Content-Length': chunkSize,
'Content-Type': 'application/octet-stream', // Adjust the content type as needed
});

// Create a readable stream to send the requested chunk
const fileStream = fs.createReadStream(filePath, { start, end });
fileStream.pipe(res);
} else {
// Standard download without resuming
res.writeHead(200, {
'Content-Type': 'application/octet-stream', // Adjust the content type as needed
'Content-Length': fileSize,
});

await pipeline(fs.createReadStream(filePath), res);
}
} catch (err) {
console.error('Error while processing download request:', err);
res.status(500).send({ error: { message: 'Internal Server Error' } });
}
}
}));


app.get('/api/browse', asyncHandler(async (req, res) => {
const curRelPath = req.query.p || '/';
Expand Down

0 comments on commit 5684598

Please sign in to comment.