Problem:
I’m facing an issue while trying to upload a picture using the following code in my Node.js application:
// Controller function for uploading pictures
const uploadPicture = async (req, res) => {
try {
const { xId } = req.params;
const file = req.file;
if (!file) {
return res.status(400).send("No file uploaded.");
}
// Define the bucket file name
const bucketFileName = `x/${xId}/${file.originalname}`;
await bucket.upload(file.buffer, {
gzip: true,
destination: bucketFileName, // Use the defined bucketFileName
metadata: {
cacheControl: "public, max-age=31536000",
contentType: file.mimetype,
},
});
const pictureData = {
x: xId,
path: `gs://${bucket.name}/${bucketFileName}`,
};
// Save the picture data to the Firestore database
await db
.collection("users")
.doc("x")
.update({
comments: admin.firestore.FieldValue.arrayUnion(pictureData),
});
res.status(200).send("Picture uploaded successfully.");
} catch (error) {
console.error("Error:", error);
res.status(500).send("Internal Server Error");
}
};
I’m getting the following error message in my application:
Error: TypeError [ERR_INVALID_ARG_VALUE]: The argument ‘path’ must be a string or Uint8Array without null bytes. Received <Buffer …>
(Console log of file is also included in the error description)
It seems that this error is related to the “path” argument when trying to upload a picture. The file object contains the following information:
{
fieldname: 'file',
originalname: 'example-preview(11).png',
encoding: '7bit',
mimetype: 'image/png',
buffer: <Buffer 89 50 4e 47 ... 10133 more bytes>,
size: 10133
}
I’m not sure why this error is occurring, and I would appreciate any insights or suggestions on how to resolve this issue.
Solution:
As you can see from the API documentation, Bucket.upload doesn’t take a buffer. It takes a string path to a file. If you have a buffer to upload, you should use File.save() instead.
See also: