Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Download File with loopback 4

I want to download a file from a loopback 4 based server. My current situation is, that i can access the file with fs.readFileSync, but it's only working for text-files. If i want to download pdf or zip files it's not working.

This is what i have so far:

export class FileController
{
    constructor(
        @repository(FileRepository) public fileRepository: FileRepository
    ){}


    @get('/files/download/{id}')
    async download(@param.path.number('id') id: number): Promise<string>
    {
        const file = await this.fileRepository.findById(id);
        const filepath = file.FilePath;

        if(!fs.existsSync(filepath))
        {
            throw new HttpErrors.NotFound(`The File #${id} can not be delivered, because the file is missing.`);
        }
        else
        {
            // @todo set headers for content type, length and caching
            return fs.readFileSync(filepath,'utf8');
        }
    }
}

If i inject RestBindings.Http.RESPONSE into the constructor, I'm able to access the response object and might edit the headers using the setHeader-Method, but with no affect.

What do i have to do to:

  1. pass the file content correctly to the client
  2. set the headers to tell the browser the correct file meta data
like image 972
MIB Avatar asked May 27 '26 20:05

MIB


1 Answers

Using this.response.download():

return await new Promise((resolve: any, reject: any) => {

    // your logic ...

    this.response.download(filepath, (err: any) => {
        if (err) reject(err);
        resolve();
    });
});

like image 135
Zhikai Xiong Avatar answered May 30 '26 08:05

Zhikai Xiong



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!