How to Perform an Http File Upload Using Express on Cloud Functions for Firebase (Multer, Busboy)

React: Multer image and data upload with using firebase function, node multer

Your client-side code looks OK.

On the server-side you can tell busboy to extract fields as well as files:

const fields = {};
const files = [];
const busboy = new Busboy({headers: req.headers});
busboy.on("field", (key, value) => (fields[key] = value));
busboy.on("file", (fieldname, file, filename, encoding, mimetype) => {/*...*/});
busboy.end(req.rawBoy);

This way you can access fields["productData"] later in your code.

Note that you need to use rawBody to access the unparsed body in Cloud Functions: https://firebase.google.com/docs/functions/http-events#read_values_from_the_request

Firebase Cloud Functions and Busboy not parsing fields or files

After further investigations, I found out that the server is working properly, while on client I need to change this line:

const response = await axios.post(`${ENDPOINT_URL}/upload`, form_data);

to:

const config = { headers: { 'content-type': `multipart/form-data; boundary=${form_data._boundary}` }};
const response = await axios.post(`${ENDPOINT_URL}/upload`, form_data, config);

Apparently, despite what stated in other posts here on SO, not specifying the multipart header doesn't cause it to be determined automatically.
Note also that if you omit the boundary setting, you will get a Boundary not found error from Busboy on the server.

Handling multipart/form-data POST with Express in Cloud Functions

Please read the documentation for handling multipart form uploads.

... if you want your Cloud Function to process multipart/form-data, you can use the rawBody property of the request.

Because of the way Cloud Functions pre-processes some requests, you can expect that some Express middleware will not work, and that's what you're running into.

multer form data req.body undefined in Express (Firebase file upload)

Turns out Firebase and multer don't go well together. I referred to this article which explains why multer does not work and how to achieve the same goal with Busboy.

https://mikesukmanowsky.com/firebase-file-and-image-uploads/



Related Topics



Leave a reply



Submit