I’m attempting to send multiple files in a multipart/form-data. This form will have one required file imagem
and on required data
which will be a json. I has a optional anexos
which is an array of images. I’m gettings an error when attempting to send only an image from axios to my nestjs backed.
From the app side I receive:
{"error": "Bad Request", "message": "Multipart: Boundary not found", "statusCode": 400}
If I remove multipart/form-data, I get an error in nestjs:
[Nest] 29165 - 01/21/2025, 10:34:06 AM ERROR [ExceptionsHandler] Cannot read properties of undefined (reading 'imagem')
TypeError: Cannot read properties of undefined (reading 'imagem')
at ReceitasController.create
React Native axios logic:
static async create(file: any, receita: Receita): Promise<Receita> {
const formData = new FormData()
formData.append('imagem', {
type: file.mime,
name: file.fileName,
uri:
Platform.OS === 'android' ? file.uri : file.uri.replace('file://', ''),
})
formData.append('data', JSON.stringify(receita))
return http.post('/receitas', formData, {
headers: { 'Content-Type': 'multipart/form-data' },
})
}
Nest.js:
@Post()
@UseInterceptors(
FileFieldsInterceptor([
{ name: 'imagem', maxCount: 1 },
{ name: 'anexos', maxCount: 5 },
]),
)
async create(
@UploadedFiles()
files: { imagem: Express.Multer.File[]; anexos?: Express.Multer.File[] },
@Body() body: { data: string },
@CurrentUser() user: TokenPayload,
) {
const file = files.imagem[0]
const b = JSON.parse(body.data)
const rc = createReceitaSchema.parse(b)
return await this.receitasService.create(
file,
rc,
user.sub,
files.anexos,
)
}
The http
is:
const http = axios.create({
baseURL: 'http://192.168.1.45:3333/',
withCredentials: true,
}) as APIInstaceProps
This works fine on my postman: