Question

How to use a WriteStream to upload to DigitalOcean Spaces

Posted September 16, 2021 47 views
Node.jsDigitalOcean SpacesBuilding on DigitalOcean

Hi, I recently was using Google Cloud storage to store my objects and I was using a WriteStream in the following way:

const imgUpload = multer({
    storage: multer.memoryStorage(),
    fileFilter: (_, file: any, callback: FileFilterCallback) => {
        if (file.mimetype == "image/jpeg" || file.mimetype == "image/png") {
            callback(null, true);
        } else {
            callback(new Error("Not an image"));
        }
    },
});

router.post(
    "/upload-img",
    expressIsAuth,
    imgUpload.single("image"),
    // @ts-ignore
    async (req: Request, res: Response) => {
        if (!req.file) {
            return res.status(500).json({ file: "No file received" });
        }
        const name = await v4();
        const blob = postPicsBuckets.file(name);
        const blobStream = blob.createWriteStream({
            resumable: false,
            gzip: true,
        });
        console.log(req.file);
        console.log(req.body);

        blobStream.on("error", (err) => {
            return res.status(500).json({ error: err.message });
        });
        blobStream.on("finish", async () => {
            const publicUrl = `https://storage.googleapis.com/${postPicsBuckets.name}/${blob.name}`;
            await Post.create({
                imgUrl: publicUrl,
                creatorId: req.session.userId,
                description: req.body.description,
            }).save();
            res.status(200).send({ url: publicUrl });
        });

        blobStream.end(req.file.buffer);
    }
);

Question

can anybody please tell me how to do such a thing with DigitalOcean Spaces where I can upload the file in the callback function and not in the Multer config itself ?

Submit an answer

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!