Search code examples
javascriptnode.jspostgresqlnestjstypeorm

Storing file in PostgreSQL database using NestJS


I have one form in React. It has many fields. once user click on the submit button all the field should be saved in database. It also contains one file attachment(pdf).

enter image description here

I dont know what the datatype of variable which will store file, I should take in entity class. Also what should be the database column type. I am using TypeORM for the same.

   @IsNotEmpty()
    @IsDate()
    endDate: Date;
    @Column()
    @IsNotEmpty()
    @IsString()
    personIncharge: string;

    @Column()
    @IsNotEmpty()
    @IsString()
    country: string;

    @Column()
    @IsNotEmpty()
    @IsString()
    comments: string;

    attachFile: string;  // Should I take file or string?

Solution

  • You will probably find your solution in this StackOverflow comment

    Basically, you turn your column type in a blob or longblob in your TypeORM annotation, and then use the type Buffer in your Entity's field

    @Column({type: 'longblob'})
    attachFile: Buffer;
    

    Then you will be able to serve the file as showed in the post example:

    app.get("/file/:id", async (req, res)=>{
        try {
            const repo = getConnection().getRepository(MYFile)
            const result_find = await repo.findOne(req.params.id)
            console.log(result_find);
            var fileData = result_find.data;
            res.writeHead(200, {
            'Content-Type': result_find.mimeType,
            'Content-Disposition': 'attachment; filename=' + result_find.name,
            'Content-Length': fileData.length
            });
            res.write(fileData);
            res.end();
        } catch (error) {
            console.log(error)
            res.send("ERROR")
        }
    })