I’m trying to figure out, what is the best way to process stream data on a nuxt server.
In the frontend, I read a file, split it up into chunks and send it to the backend. But I’m not sure, how to handle stream data at server side. Does anyone has an idea?
<template>
<div>
<input
type="file"
@input="onUpload"
/>
</div>
</template>
<script setup lang="ts">
const onUpload = ({files: File[]}): void => {
const uploadFile = files.at(0);
console.log('upload file', uploadFile);
if (!uploadFile) return;
const fileReader = new FileReader();
fileReader.readAsArrayBuffer(uploadFile);
fileReader.onload = async (event) => {
if (!event?.target?.result) return;
// file content
const content = event.target.result;
// fix chunk size
const CHUNK_SIZE = 5000;
// total chunks
const totalChunks = event.target.result.byteLength / CHUNK_SIZE;
// loop over each chunk
for (let chunk = 0; chunk < totalChunks + 1; chunk++) {
// prepare the chunk
let CHUNK = content.slice(
chunk * CHUNK_SIZE,
(chunk + 1) * CHUNK_SIZE
) as
await $fetch('/api/upload', {
method: 'post',
headers: {
contentType: 'application/octet-stream',
contentLength: CHUNK.byteLength.toString(),
},
body: CHUNK,
});
}
console.log('Complete File read successfully!');
};
};
</script>