DEV Community

KISHAN RAMLAKHAN NISHAD
KISHAN RAMLAKHAN NISHAD

Posted on

1

handleBase64Upload

const rp = require('request-promise');

const baseUrl = "https://uotmnewuat.icicibank.com/UOTM_data/api/upload";

const handleBase64Upload = (folder) => {
  return async (req, res, next) => {
    try {
      if (req.body.thumbmail) {
        console.log("Processing Base64 image");

        let fileType;
        let base64Data = req.body.thumbmail;

        // Check if the Base64 string has a prefix
        const matches = base64Data.match(/^data:(.+);base64,(.+)$/);
        if (matches && matches.length === 3) {
          const mimeType = matches[1]; // Extract MIME type (e.g., image/jpeg)
          fileType = mimeType.split('/')[1]; // Extract file extension (e.g., jpeg, png)
          base64Data = matches[2]; // Extract Base64 content
        } else {
          throw new Error("Invalid Base64 format. Missing data URI prefix.");
        }

        // Prepare the file for upload
        const fileBuffer = Buffer.from(base64Data, 'base64');
        const fileName = `thumbmail_${Date.now()}.${fileType}`;

        // Upload the file to Azure
        const options = {
          uri: baseUrl,
          method: 'POST',
          formData: {
            folder,
            image: {
              value: fileBuffer,
              options: {
                filename: fileName,
                contentType: `image/${fileType}`
              }
            }
          },
          json: true
        };

        const response = await rp(options);

        if (response.StatusCode === 100) {
          console.log("File uploaded successfully:", response.Data);
          req.body.thumbmail = response.Data; // Update request body with the Azure URL
        } else {
          throw new Error(response.Message || "Failed to upload file to Azure");
        }
      }

      next();
    } catch (error) {
      console.error("Error handling Base64 upload:", error.message);
      res.status(400).json({ message: 'Failed to process and upload Base64 image', error: error.message });
    }
  };
};

module.exports = handleBase64Upload;

Enter fullscreen mode Exit fullscreen mode

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more