MIB
MIB

Reputation: 347

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

Upvotes: 3

Views: 1561

Answers (1)

Zhikai Xiong
Zhikai Xiong

Reputation: 397

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();
    });
});

Upvotes: 3

Related Questions