main.js 注册fastify-multipart, 设置addToBody为true
app.register(require('fastify-multipart'), {
addToBody:true
})
controller层拿到相应的数据
@Put(':id')
async edit(
@Req() req: FastifyRequest,
@Param('id') libraryId: string,
@Query() libraryQuery: any,
) {
const data = req.body;
return this.artifactsLibraryService.edit(libraryId, libraryQuery, data);
}
service层写相应的逻辑,最重要的是上传证书这步uploadCertificate
async edit(id, params, multipart) {
const data = {};
const file = multipart.file;
Object.keys(multipart).forEach(key => {
if (key != 'file') {
data[key] = multipart[key];
}
});
const assignQuery: any = this.getLibraryAssignQuery();
const obj: any = this.getLibraryObj(data);
const assignObj: any = this.getLibraryAssignObj(data, params);
await this.httpRequest(LibraryApi.updata(id, obj)).toPromise();
const assignResp = await this.httpRequest(
LibraryApi.assignPage(assignQuery),
).toPromise();
const assignInfo = assignResp['rows'].find(row => {
return row.credentialId == id;
});
if (assignInfo) {
await this.httpRequest(
LibraryApi.assignUpdate(id, assignInfo.id, assignObj),
).toPromise();
}
if (file && file !== 'undefined') {
await this.uploadCertificate(file, id);
}
return true;
}
//重要的是先写入流 然后再读流,把读到的数据append到formData的对象中
private async uploadCertificate(file, id) {
const writerStream = createWriteStream(
join(__dirname, `${file[0].filename}`),
);
writerStream.write(file[0].data);
await writerStream.end();
const readerStream = createReadStream(join(__dirname, `${file[0].filename}`));
const fileFormData = new FormData();
fileFormData.append('file', readerStream);
await this.upload(id, fileFormData).toPromise();
unlink(join(__dirname, `${file[0].filename}`), function(err) {
console.error(err);
});
}