Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

802
Visualizações
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?
over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

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")
    }
})
over 4 years ago · Santiago Trujillo Relatório

0

if you want using string, client must send base64 file to backend.
format: data:(mimetype);(charset),(encoded) -> data:image/png;base64,\ee\9f920d....

here solution, using base64 string
DTO (data transfer object)

import { IsDefined, IsNotEmpty } from 'class-validator';

export class UpdateUserAvatarDto {
  @IsDefined()
  @IsNotEmpty()
  file: string;
}

controller

@UseGuards(JwtAuthGuard)
@Patch('account/avatar')
async updateAvatar(
    @User() user: Payload,
    @Body() updateUserAvatarDto: UpdateUserAvatarDto,
    @Res() res: Response,
  ) {
    try {
      const { file } = updateUserAvatarDto;

      createFile(file, { prefix: ['user', 'avatar'], name: user.id }); // file is string base64 you can store it to database.

      return response(res, HttpStatus.OK, {
        message: 'Successfully update avatar',
      });
    } catch (e) {
      console.error(e);
      return response(res, HttpStatus.INTERNAL_SERVER_ERROR, {
        message: e,
        data: null,
      });
    }
}

if you want to create a file from base64

export const createFile = async (base64, { prefix, name }) => {
  const cleanBase64 = base64.split(',')[1];
  const buffer = Buffer.from(cleanBase64, 'base64');
  const file = await fileType.fromBuffer(buffer);
  return fs.writeFileSync(
    path.join(
      path.resolve('./'),
      ...['public', ...prefix, `${name}.${file.ext}`],
    ),
    buffer,
  );
};
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda