【问题标题】:Need to upload file in PostgreSQL database using TypeORM/NestJS需要使用 TypeORM/NestJS 在 PostgreSQL 数据库中上传文件
【发布时间】:2021-12-19 07:13:10
【问题描述】:

谁能帮忙解决这个问题。

我需要使用 TypeORM/NestJS 将文件上传到 PostgreSQL 数据库。文件是表单的一部分。

我已经采取了以下实体类。

export class Certificate {
    @ApiProperty()
    @PrimaryGeneratedColumn()
    @Exclude()
    id: number;
    @ApiProperty()
    @Column({ type: 'varchar', length: 15 })
    statusOfReport: string;

    @ApiProperty()
    @Column({ type: 'varchar', length: 100 })
    sponser: string;

    @ApiProperty()
    @Column({ type: 'varchar', length: 100 })
    address: string;

    @ApiProperty()
    @Column({ type: 'varchar', length: 100 })
    address2: string;
    @ApiProperty()
    @Column()
    zipCOde: string;

    @ApiProperty()
    @Column()
    city: string;

    @ApiProperty()
    @Column()
    protoColNo: string;

    @ApiProperty()
    @Column()
    molecules: string;

    @ApiProperty()
    @Column()
    unAuthMolecule: string;

    @ApiProperty()
    @Column()
    phaseOfTrial: number;

    @ApiProperty()
    @Column()
    noOfSubjects: number;

    @ApiProperty()
    @Column()
    startDate: Date;

    @ApiProperty()
    @Column()
    endDate: Date;

    @ApiProperty()
    @Column()
    personInCharge: string;

    @ApiProperty()
    @Column()
    country: string;

    @ApiProperty()
    @Column()
    comments: string;

    @ApiProperty()
    @Column({ type: 'bytea' })
    attachFile: Uint8Array;

下面是我的控制器方法。

@Post()
create(@Body() createCertificateDto: CreateCertificateDto): Promise<Certificate> {
    return this.certificatesService.create(createCertificateDto);
}

下面是我的服务类方法。

async create(createCertificateDto: CreateCertificateDto): Promise<Certificate> {
    return this.certificateRepository.save(createCertificateDto);
}

我正在将文件保存为数据。我需要做哪些更改才能在数据库中上传文件。文件可以是excel, pdf, text 等。现有的答案没有帮助。

【问题讨论】:

  • 我使用的是 13.1。我只是将标签用于更广泛的受众。
  • 好吧,as documented in the manual pg_read_file 返回 text,而不是 bytea 您需要使用 pg_read_binary_file - 但只有在运行 pgAdmin 的计算机上也运行 Postgres 时才有效

标签: node.js postgresql rest nestjs typeorm


【解决方案1】:

在您的控制器上:

import {
    Controller,
    Post,
    Body,
    Patch,
    Param,
    Get,
    Delete,
    UsePipes,
    Query,
    Request,
    UseInterceptors, UploadedFile, UseGuards,
    } from '@nestjs/common';
   import {FileInterceptor} from '@nestjs/platform-express';
   import { extname, join } from 'path';
   import { diskStorage } from 'multer';

   @Post()
   @UseInterceptors(FileInterceptor('file', {
     storage: diskStorage({
     destination: './uploads/files',
     filename: (req, file, cb) => {
        const randomName = Array(32).fill(null).map(() => 
       (Math.round(Math.random() * 16)).toString(16)).join('');
         return cb(null, `${randomName}${extname(file.originalname)}`);
         },
       }),
      }))
     create(
     @Body() createCertificateDto: CreateCertificateDto, 
     @UploadedFile() file): Promise<Certificate> {
        return this.certificatesService.create(createCertificateDto, file);
    }

将实体更新为:

 @Column({ type: 'varchar', length: 300, nullable: true })
   attachFile: string;

或者你坚持将文件名字符串转换为ByteArray,即Uint8Array

这里是服务:

async create(createCertificateDto: CreateCertificateDto, file): Promise<any> {
console.log(file);
console.log(createCertificateDto);
 try{
     const cert = new Certificate();
        cert.statusOfReport = createCertificateDto?.statusOfReport;
        cert.sponser = createCertificateDto?.sponser;
        cert.address = createCertificateDto?.address;
        cert.address2 = createCertificateDto?.address2;
        cert.zipCOde = createCertificateDto?.zipCOde;
        cert.city = createCertificateDto?.city;
        cert.protoColNo = createCertificateDto?.protoColNo;
        cert.molecules = createCertificateDto?.molecules;
        cert.unAuthMolecule = createCertificateDto?.unAuthMolecule;
        cert.phaseOfTrial = createCertificateDto?.phaseOfTrial;
        cert.noOfSubjects = createCertificateDto?.noOfSubjects;
        cert.startDate = createCertificateDto?.startDate;
        cert.endDate = createCertificateDto?.endDate;
        cert.personInCharge = createCertificateDto?.personInCharge;
        cert.country = createCertificateDto?.country;
        cert.comments = createCertificateDto?.comments;
        cert.attachFile = (file) ? file.filename : '';
        cert.statusOfReport = createCertificateDto?.statusOfReport;
        await cert.save();
        return {success: true, cert};
    } catch (e) {
        return {success: false, message: e.message};
    }
 }

我希望这对您有所帮助。如果对实施有任何疑问,可以与我联系。

【讨论】:

    【解决方案2】:

    据我所知,您缺少控制器上的文件装饰器。

    @Post()
    @UseInterceptors(FileInterceptor('file'))
    create(@Body() createCertificateDto: CreateCertificateDto, @UploadedFile() file: any): Promise<Certificate> {
        return this.certificatesService.create(createCertificateDto, file);
    }
    

    您可能还想查看此StackOverflow 以了解 TypeORM 方面的情况。

    【讨论】:

    • 你能帮我看看服务层的代码吗?保存是否允许添加 2 个参数?如何序列化/反序列化文件?
    猜你喜欢
    • 2021-12-17
    • 2019-05-09
    • 1970-01-01
    • 2019-01-30
    • 1970-01-01
    • 1970-01-01
    • 2019-06-19
    • 2019-02-01
    • 2021-05-03
    相关资源
    最近更新 更多