Downloading data
To make the data available we first need to implement our get function in lib/server/files.ts:
import { Readable } from 'node:stream';
// ...
export function get(name: string) {
const filename = path.join(base, name);
return Readable.toWeb(fs.createReadStream(filename));
} With that, we can make the data available with a new server route, /file/[id]/download/+server.ts:
import { getFile } from '$lib/files.remote.js';
import { get } from '$lib/server/files.js';
export async function GET({ params }) {
const d = await getFile(params.id);
return new Response(get(`${d.user_id}/${d.id}`) as ReadableStream, {
headers: {
'content-type': d.type
}
});
} On the server, our remote function is just a function — we’re calling it directly, not over HTTP.
If we manually visit the download route, we can see that it’s working. All we need to do now is update the src:
<img alt={data.name} src={resolve('/file/[id]/download', { id: data.id })} />