#How to save images inside a local storage?

92 messages · Page 1 of 1 (latest)

analog tundraBOT
#
  • Consider reading #how-to-get-help to improve your question!
  • Explain what exactly your issue is.
  • Post the full error stack trace, not just the top part!
  • Show your code!
  • Issue solved? Press the button!
empty pond
#

thats not how i told you to fetch

#

nor is MessageAttachment v14

gloomy sapphire
gloomy sapphire
empty pond
#

if you want it to work yes

#

put some effort in

gloomy sapphire
empty pond
#

its optional

gloomy sapphire
#

okay thanks
I'll come back when I finish reading it

gloomy sapphire
# empty pond https://bork.treble-is-fluffy.gay/floofabc15cc5.png

I swear by god that I understood nothing from it
I don't even know what you want me to use as an option
Looking at this example means.... nothing to me, I don't understand what I should do different in my codejs const myInit = { method: "GET", headers: myHeaders, mode: "cors", cache: "default", };
Please just tell me what i need to use there, this is waaaay too complex for a beginner

gloomy sapphire
empty pond
#

then maybe dont try something that complex if you cant understand it

gloomy sapphire
empty pond
#

for you apparently

#

i woudl recommend searching some guides on how to use node:fetch

gloomy sapphire
#

😖

#

okay

magic tendon
gloomy sapphire
magic tendon
gloomy sapphire
#

Then why did I have to read that doc that made everything the more complicated for me 😖

gloomy sapphire
gloomy sapphire
#

I got stuck with this for eternity it feels like

lofty socket
#

I don’t think that’s a function…?

#

const data = await fetch(someURL)
const buffer = await data.arrayBuffer()

Will work for an arrayBuffer(), fetch is native for node versions > v18 or something

#

Oh I’m stupid forget that I see the code at the bottom

#

Try using native fetch rather then node-fetch. Other then that sorry that I didn’t see the other code haha

magic tendon
#

instead of

const files = attachments.map(...);
for (const file of files) {...}

you can also use

for (const [id, attachment] of attachments) {...}

if you'd like to

magic tendon
gloomy sapphire
magic tendon
#

Ig you are not very familiar with promises

gloomy sapphire
magic tendon
#

They are already inside a async function

gloomy sapphire
#
  Type 'Promise<ArrayBuffer>' is missing the following properties from type 'DataView': buffer, byteLength, byteOffset, getFloat32, and 19 more.ts(2345)
const buffer: Promise<ArrayBuffer>```
#

I still get the same error for buffer

#
import fs from "fs";
import fetch from "node-fetch";
import path from "path";

import { Message } from "discord.js";

export default async function saveImages(message: Message<true>) {
  // Primary --------------------------------------------------------------------------------------
  const { channel, attachments, content } = message;

  try {
    if (channel.id !== "1148740978170146948") return;
    if (!content.includes("!ns")) return;
    if (message.attachments.size <= 0) return;

    // Second
    const imageURLs = attachments.map((image) => image.url);
    const filePath = "./some_folder/images.zip";

    async function downloadAttachmentTwo(imageURLs: string[], filePath: string) {
      //
      for (const imageURL of imageURLs) {
        //
        const response = await fetch(imageURL);

        const buffer = await response.arrayBuffer();

        const directoryPath = path.dirname(filePath);

        if (!fs.existsSync(directoryPath)) {
          fs.mkdirSync(directoryPath, { recursive: true });
        }

        fs.writeFileSync(filePath, buffer, () => console.log("Attachment saved successfully!"));

        //
      }
    }

    return downloadAttachmentTwo(imageURLs, filePath);
    //
  } catch (error) {
    console.log(error);
  }
}
gloomy sapphire
magic tendon
#

Yes

gloomy sapphire
#

because if yes it's still teh same

magic tendon
#

The type error?

gloomy sapphire
#
import fs from "fs";
import fetch from "node-fetch";
import path from "path";

import { Message } from "discord.js";

export default async function saveImages(message: Message<true>) {
  // Primary --------------------------------------------------------------------------------------
  const { channel, attachments, content } = message;

  try {
    if (channel.id !== "1148740978170146948") return;
    if (!content.includes("!ns")) return;
    if (message.attachments.size <= 0) return;

    // Second
    const imageURLs = attachments.map((image) => image.url);
    const filePath = "./some_folder/images.zip";

    async function downloadAttachmentTwo(imageURLs: string[], filePath: string) {
      //
      for (const imageURL of imageURLs) {
        //
        const response = await fetch(imageURL);

        const buffer = await response.arrayBuffer();

        const directoryPath = path.dirname(filePath);

        if (!fs.existsSync(directoryPath)) {
          fs.mkdirSync(directoryPath, { recursive: true });
        }

        fs.writeFileSync(filePath, buffer, () => console.log("Attachment saved successfully!"));

        //
      }
    }

    return downloadAttachmentTwo(imageURLs, filePath);
    //
  } catch (error) {
    console.log(error);
  }
}

``````Argument of type 'ArrayBuffer' is not assignable to parameter of type 'string | ArrayBufferView'.
  Type 'ArrayBuffer' is missing the following properties from type 'DataView': buffer, byteOffset, getFloat32, getFloat64, and 18 more.ts(2345)
const buffer: ArrayBuffer```
gloomy sapphire
#

is there an alternative buffer for this maybe?
Something else than .arrayBuffer()

magic tendon
#

Need to read

gloomy sapphire
#

I can't believe it's this hard to save an image in local storage 😦

lofty socket
#

Is that all you’re trying to do?

gloomy sapphire
#

But I couldn't find any examples of it

#

and without examples I jsut can't do anything

#

I can't learn without examples 😦

lofty socket
#

U wrote a function for that a while back

#

Let me see if I can find

#

I*

gloomy sapphire
#

Me?

#

I really don't remember

lofty socket
#

I* typo

gloomy sapphire
#

Oh you okay

#

That would be very very nice

#

I'm stuck at this since a couple days 🙂

magic tendon
gloomy sapphire
magic tendon
lofty socket
#

You don’t need to use a zip file lol

gloomy sapphire
#

I just want to store the images inside a local storage

#

that's all

gloomy sapphire
#

But @lofty socket
I'm hosting my but most of the time on a server
Will that local storage work even then?

gloomy sapphire
#

ty

#

I'll try it

magic tendon
lofty socket
#

I can’t seem to find it, but I know I used native fetch and then just .arrayBuffer() it

gloomy sapphire
#

Thanks, I'm trying it rn

gloomy sapphire
#

It works... finally 🙂
Here is the code of someone else needs it in the future:

import fs from "fs";
import fetch from "node-fetch";

import { Message } from "discord.js";

export default async function saveImages(message: Message<true>) {
  // Primary --------------------------------------------------------------------------------------
  const { channel, attachments, content } = message;

  function hasAttachment() {
    console.log("Checking attachment...");

    if (message.attachments.size > 0) {
      console.log("Attachment detected.");
      return true;
    } else {
      console.log("Unable to detect any attachments.");
      return false;
    }
  }

  try {
    if (channel.id !== "1148740978170146948") return;

    if (!content.includes("!ns")) return;

    if (!hasAttachment()) return;

    async function savePhotoFromAPI() {
      //
      const urls = attachments.map((attachment) => attachment.url);

      for (const url of urls) {
        //
        const response = await fetch(url);

        const arrayBuffer = await response.arrayBuffer();

        const buffer = Buffer.from(arrayBuffer);

        if (url.includes(".png") || url.includes(".jpg")) {
          //
          const ext = url.includes(".png") ? ".png" : ".jpg";
          let i = 1;
          let outputFileName = `testSaveImages${ext}`;

          while (fs.existsSync(outputFileName)) {
            outputFileName = `testSaveImages_${i}${ext}`;
            i++;
          }

          fs.createWriteStream(outputFileName).write(buffer);
          //
          return Promise.resolve("Attachement has been saved?");
        } else {
          return Promise.reject(
            "File type could not be reliably determined! The binary data may be malformed! No file saved!"
          );
        }
      }
    }

    await savePhotoFromAPI()
      .then((msg) => console.log(msg))
      .catch((msg) => console.log(msg));

    //
  } catch (error) {
    console.log(error);
  }
}
#

How to save images inside a local storage?

lofty socket
# gloomy sapphire It works... finally 🙂 Here is the code of someone else needs it in the future: ...

I found what I done before,

async function savefile(url) {
    await fetch(url).then(async (res) => {
        const d = await res.arrayBuffer();
        const buffer = Buffer.from(d);
        const type = res.headers.get('Content-Type')?.split('/')?.[1]
        const { writeFile } = require('node:fs');
        writeFile('filename' + type, buffer, { encoding: 'base64' }, function (err) {
            if(err) throw err;
            console.log('done')
        })
    })
}

the type was from the headers but idk how you get the name but that's down to your discretion with how you wanna handle that tbf

gloomy sapphire