download file from a folder

I have a folder on my machine with some reports. I want my connected users to be able to download these files. How can I create a protected api route that send the files, so it can be download from the client ? here is what I tried :
export const downloadFilesRouter = createTRPCRouter({
getFileContent: publicProcedure
.input(
z.object({
filename: z.string(),
})
)
.query(({ input }) => {
const { filename } = input;
const filePath = path.join(folderPath, filename);
const imageBuffer = readFileSync(filePath);
return imageBuffer;
}),
});
export const downloadFilesRouter = createTRPCRouter({
getFileContent: publicProcedure
.input(
z.object({
filename: z.string(),
})
)
.query(({ input }) => {
const { filename } = input;
const filePath = path.join(folderPath, filename);
const imageBuffer = readFileSync(filePath);
return imageBuffer;
}),
});
on the client :
const FileDownloadList: React.FC = () => {
const data = api.downloadFiles.getFileContent.useQuery({
filename: "file1.txt",
});
console.log(data);

return (
<div>
...
</div>
);
};

export default FileDownloadList;
const FileDownloadList: React.FC = () => {
const data = api.downloadFiles.getFileContent.useQuery({
filename: "file1.txt",
});
console.log(data);

return (
<div>
...
</div>
);
};

export default FileDownloadList;
The result : an error "TRPCClientError: Unable to transform response from server" and the data is undefined
Solution:
You should change to base64 and decode on frontend
Jump to solution
3 Replies
Neto
Neto16mo ago
You can't serialize a direct buffer
Solution
Neto
Neto16mo ago
You should change to base64 and decode on frontend
Romain
Romain16mo ago
thank you very much, it works perfectly now !
Want results from more Discord servers?
Add your server