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);
});
}