在你的控制器中:
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
i.e 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};
}
}
我希望你觉得这有帮助。如果您对实施有任何疑问,可以联系我。