Basically I have an external api for campaign update. Each campaign contains a image. That API expects image as file from my end. (jps,jpeg,svg,png,GIF format). I already did post api and its working fine. but in my update api its being success but values are not changing. here I am attaching my code.
Controller:
@Put(':id')
@ApiFile('image')
@ApiBody({ type: UpdateCampaignDto })
async update(
@UploadedFile() image: Express.Multer.File,
@Param('id') id: string,
@Body() updateCampaignDto: UpdateCampaignDto,
) {
try {
const payload = await this.campaignService.update(+id, updateCampaignDto,image);
return { message: 'Campaign Updated successfully!', payload };
} catch (error) {
throw new BadRequestException('Error updating campaign');
}
}
Service:
async update(id: number, updateCampaignDto: UpdateCampaignDto, image: Express.Multer.File) {
const formData = new FormData();
if (image) {
const imageStream = streamifier.createReadStream(image.buffer);
formData.append('image_url', imageStream, {
filename: image.originalname,
contentType: image.mimetype,
});
}
for (const key in updateCampaignDto) {
let value = updateCampaignDto[key];
if (key === 'start_date' || key === 'end_date') {
value = moment(value).format('YYYY-MM-DD');
}
if (Array.isArray(value)) {
value.forEach((item) => {
formData.append(`${key}[]`, item.toString());
});
}
else if (typeof value === 'object' && value !== null) {
formData.append(key, JSON.stringify(value));
}
else {
formData.append(key, value.toString());
}
}
const url = `${process.env.COUPON_URL}/api/v1/campaigns/${id}`;
const authenticateResponse = await this.authenticate();
try {
const response = await axios.put(
url,
formData,
{
headers: {
Accept: 'application/json',
Authorization: `Bearer ${authenticateResponse.access_token}`,
...formData.getHeaders(),
},
},
);
return response.data;
} catch (error) {
throw new Error('Failed to update campaign');
}
}
This api is working without formdata.