dropbox / dropbox-sdk-js

The Official Dropbox API V2 SDK for Javascript
https://www.dropbox.com/developers
MIT License
941 stars 353 forks source link

nextjs upload file Dropbox API #1131

Closed iscorporacion closed 8 months ago

iscorporacion commented 1 year ago

I am using nextjs 13, I follow the example in the documentation, they recommend using isomorphic-unfetch, but no matter how hard I try, the same error Module not found: Can't resolve 'unfetch' persists

import { Dropbox, Error, files } from 'dropbox';
import 'isomorphic-unfetch';

const uploadFile = async ({ file, filePath, directorio }: { file: string, filePath: string, directorio?: string }) => {

    const dbx = new Dropbox({ accessToken });

    try {
        const fileContents = fs.readFileSync(filePath);

        // Subir el archivo a Dropbox
        await dbx.filesUpload({
          path: `/Media/${file}`,
          contents: fileContents,
        });

        console.log('Archivo subido a Dropbox con éxito.');
      } catch (error) {
        console.error('Error al subir el archivo a Dropbox:', error);
      }

}

image

https://www.dropbox.com/developers/documentation/javascript#install

greg-db commented 1 year ago

I don't believe this library was explicitly tested with 'isomorphic-unfetch' in particular, but regardless it looks like that error is occurring in the isomorphic-unfetch code, not the Dropbox code, so I recommend reaching out to the isomorphic-unfetch maintainers, or the unfetch maintainers, for help with that error.

decovicdev commented 11 months ago

@iscorporacion This code snippet is a TypeScript and nextjs function that utilizes the Dropbox SDK

and this is how I solved the fetch error.

import { Dropbox } from "dropbox";

import { env } from "@/validation/env";
import { Account } from "@/types/db";

export default function dropbox(account: Account) {
  if (!account) {
    throw new Error("Dropbox account not found");
  }

  const customFetch = async (input: RequestInfo, init?: RequestInit): Promise<Response> => {
    const response = await globalThis.fetch(input, init);

    return Object.defineProperty(response, "buffer", {
      value: response.arrayBuffer,
    });
  };

  return new Dropbox({
    fetch: customFetch,
    clientId: env.DROPBOX_ID,
    clientSecret: env.DROPBOX_SECRET,
    accessToken: account.access_token!,
    refreshToken: account.refresh_token!,
  });
}

remember to treat the buffer as an arrayBuffer and not buffer if you want to save to fs.

const nodeBuffer = Buffer.from(arrBuffer);
iscorporacion commented 8 months ago

@decovicdev thanks for your response, this an exceptionally fine response and is ok for me, is working right now