I'm running a small api with nuxt3/nitro. It works like a proxy between my webapp and my regular api. So my nitro api receives files, I read them from the request using Formidable, and they get saved in formidable's PersistentFile
instances.
Now I need to put these files in a regular formData.append syntax, so I can use the fetch api to send a post containing these files in the formData.
How can I do this? If I just put the file like formData.append('name', persistentFileInstance);
it says it isn't recognized as a file. So I'm kinda lost on how should I transform this instance.
Here's a console.log of my file:
addImage.post.ts called with this content { 19:33:43
photo: [
PersistentFile {
_events: [Object: null prototype],
_eventsCount: 1,
_maxListeners: undefined,
lastModifiedDate: 2023-01-07T22:33:43.127Z,
filepath: '/tmp/0d0c99ee783bfe790d86da001',
newFilename: '0d0c99ee783bfe790d86da001',
originalFilename: 'Screenshot from 2023-01-04 09-04-32.png',
mimetype: 'image/png',
hashAlgorithm: false,
size: 110657,
_writeStream: [WriteStream],
hash: null,
[Symbol(kCapture)]: false
}
]
}
I fixed it by creating a buffer from the local file path, then a Blob instance, then appending the Blob to the FormData. Here's my code:
import { readFiles } from 'h3-formidable'
import { Blob } from "buffer";
import fs from "fs";
//...
let buffer = fs.readFileSync(thisPhoto.filepath);
let blob = new Blob([buffer]);
var form = new FormData(); //this is default FormData instance, not the custom package
form.append('photo', blob);