I have the following code, I would like to take the uploaded file and pass it through to an api as a Byte array, is this possible?
interface IData{
file: Uint8Array
}
const [open, setOpen] = React.useState(false);
<div>
<Button variant="contained" color="primary" onClick={() => setOpen(true)}>
Add Data
</Button>
<DropzoneDialog
acceptedFiles={['image/*']}
cancelButtonText={"cancel"}
submitButtonText={"submit"}
maxFileSize={5000000}
open={open}
onClose={() => setOpen(false)}
onSave={(files) => {
let data = {} as IData;
data.file = files[0];
// Call api here... but
setOpen(false);
}}
showPreviews={true}
showFileNamesInPreview={true}
/>
but on the line data.file = files[0]
I get the following error
Type 'File' is missing the following properties from type 'Uint8Array': BYTES_PER_ELEMENT, buffer, byteLength, byteOffset, and 25 more.ts(2740)
What is the the best way to get the uploaded file as a byte array?
You need to make use of FileReader
with readAsArrayBuffer
to convert the file object to a byte array
onSave={(files) => {
const reader = new FileReader();
reader.addEventListener('load', () => {
let data = {} as IData;
data.file = new Uint8Array(reader.result as ArrayBuffer);
// call api here
setOpen(false);
});
reader.readAsArrayBuffer(files[0]);
}