exports.app = onRequest({cors: true}, (req, res) => {
const form = formidable({ multiples: true, maxFileSize: 15 * 1024 * 1024 });
form.parse(req, (err, fields, files) => {
if (err) {
logger.error(err);
res.status(500).send({ error: 'Failed to parse form' });
} else {
const dataSourceString = fields['dataSource[]'];
var dataSourceList = JSON.parse(dataSourceString);
const fileList = files['attachment[]'];
fileList.forEach((file, index) => {
// Modify filename as needed
const parts = file.name.split('.');
const name = parts[0]; // Filename without extension
const extension = parts.slice(1).join('.'); // File extension
var fileName = dataSourceList[index].docType;
fileName = fileName.replace(///g, " ");
file.name = `${fileName}.${extension}`;
});
const ticketData = {
subject: 'Test',
description: fields.description,
priority: 1,
status: 2,
email: fields.email,
};
function formatDate(date) {
return new Date(date).toISOString();
}
const formData = new FormData();
formData.append('subject', ticketData.subject);
formData.append('description', ticketData.description);
formData.append('priority', ticketData.priority);
formData.append('status', ticketData.status);
formData.append('email', ticketData.email);
fileList.forEach((file) => {
const stream = fs.createReadStream(file.path);
const blob = new Blob([stream], { type: file.type });
formData.append('attachments[]', blob, {
filename: file.name,
contentType: file.type,
});
});
const configData = {
method: 'post',
url: config.fsURL + '/api/v2/tickets',
headers: {
'Authorization': 'Basic ' + Buffer.from(config.fsAPIKey + ':x').toString('base64'),
'Content-Type': 'multipart/form-data'
},
data : formData
};
axios(configData)
.then(function (response) {
console.log(response.data);
res.status(200).json(response.data);
})
.catch(function (error) {
console.log('Error:', error.toJSON());
});
}
});
});
I have code as above and it seems to work fine for all fields. However there seems to be some problem when I try to upload multiple attachments. It doesn’t seem to be inserting files correctly as I am getting attachments as [[Object], [Object]] when return after create ticket.
Details can be shown as below. Anyone have any idea how this can be done?