cloudinary / cloudinary-react-native

MIT License
13 stars 6 forks source link

File upload function #10

Closed Presleyderrick closed 6 months ago

Presleyderrick commented 1 year ago

upload does not seem to work for me, how can I import upload because when I don't I get " Cannot find name 'upload'. "

tamaracloudinary commented 1 year ago

Hi there, make sure your code is set up correctly, you can use the upload example here: https://github.com/cloudinary/cloudinary-react-native#usage If it's set correctly and there is an issue, can you please share your code here? Thanks -Tamara

Presleyderrick commented 1 year ago

Hi,

this is my code

import { PermissionsAndroid, Text, View } from 'react-native' import React, { Component, useState } from 'react' import {Cloudinary} from @.***/url-gen'; import { launchCamera } from 'react-native-image-picker';

const cld = new Cloudinary({ cloud: { cloudName: '' }, url: { secure: true } });

const uploademp =()=> {
    const [photoPath, setPhotoPath] = useState<string | undefined>(

undefined);

    const cloudinaryUpload = async () => {

          const options: UploadApiOptions = {
            upload_preset: 'sample_preset',
            unsigned: true,
          }

            await upload(cld, {file: photoPath , options: options,

callback: (error: any, response: any) => { //.. handle response }}) };

        const openCamera = async () => {
            const granted = await PermissionsAndroid.request(
              PermissionsAndroid.PERMISSIONS.CAMERA,
            );
            if (granted === PermissionsAndroid.RESULTS.GRANTED) {
              const result = await launchCamera(options);
              // const currentDate = new Date();
              // const formattedDate = format(currentDate,

'yyyyMMddHHmmss'); // const newPhotoPath = e_permit${formattedDate}.jpg;

              try {
                if (result && result.assets && result.assets[0]) {
                  // const newPath =

${RNFS.DocumentDirectoryPath}/${newPhotoPath}; // await RNFS.moveFile(result.assets[0].uri, newPath); setPhotoPath(result.assets[0].uri); // console.log("response is:", uri); const base64Image = result.assets[0].base64; // console.log('Error renaming photo:', base64Image); const source = { base64Image }; cloudinaryUpload(); } else { console.log('result.assets is undefined or empty.'); } } catch (error) { console.log('Error:', error); } } };

{
    return (
    <View>
        <Text>uploademp</Text>
    </View>
    )
}

}

export default uploademp

and this is what I am receiving from my error

Cannot find name 'upload'.ts(2304) any

Kindly advise on where the error seems to emanate from since I cannot be able to find any import statement for the upload

Regards, Presley Derrick. [image: Mailtrack] https://mailtrack.io?utm_source=gmail&utm_medium=signature&utm_campaign=signaturevirality11& Sender notified by Mailtrack https://mailtrack.io?utm_source=gmail&utm_medium=signature&utm_campaign=signaturevirality11& 08/15/23, 12:47:32 PM

On Tue, 15 Aug 2023 at 12:09, tamaracloudinary @.***> wrote:

Hi there, make sure your code is set up correctly, you can use the upload example here: https://github.com/cloudinary/cloudinary-react-native#usage If it's set correctly and there is an issue, can you please share your code here? Thanks -Tamara

— Reply to this email directly, view it on GitHub https://github.com/cloudinary/cloudinary-react-native/issues/10#issuecomment-1678631939, or unsubscribe https://github.com/notifications/unsubscribe-auth/ASYXCJIYCLO33RRUKTIZHJTXVM4ERANCNFSM6AAAAAA3PKNULA . You are receiving this because you authored the thread.Message ID: @.***>

tamaracloudinary commented 1 year ago

In your code, you have to update the 'upload_preset' with your own, the cloud name with your own and import Cloudinary this way: import {Cloudinary} from '@cloudinary/url-gen';. Also, implement what happens inside the upload function. Please try these and let me know how it goes. Thanks,

Presleyderrick commented 1 year ago

Hello,

This is what I have

import { PermissionsAndroid, Text, View } from 'react-native' import React, { Component, useState } from 'react' import {Cloudinary} from @.***/url-gen'; import { launchCamera } from 'react-native-image-picker';

const cld = new Cloudinary({

cloud: { cloudName: 'dtauszhrv'  },

url: { secure: true }

});

interface UploadApiOptions { upload_preset: string; unsigned: boolean; }

const uploademp =()=> {
    const [photoPath, setPhotoPath] = useState<string | undefined>(

undefined);

    const cloudinaryUpload = async () => {

const cloudoptions: UploadApiOptions = {

upload_preset: 'e-permit',

unsigned: true,

}

            await upload(cld, {file: photoPath , options: options,

callback: (error: any, response: any) => { //.. handle response }}) };

        const openCamera = async () => {
            const granted = await PermissionsAndroid.request(
              PermissionsAndroid.PERMISSIONS.CAMERA,
            );
            if (granted === PermissionsAndroid.RESULTS.GRANTED) {
              const result = await launchCamera(options);
              // const currentDate = new Date();
              // const formattedDate = format(currentDate,

'yyyyMMddHHmmss'); // const newPhotoPath = e_permit${formattedDate}.jpg;

              try {
                if (result && result.assets && result.assets[0]) {
                  // const newPath =

${RNFS.DocumentDirectoryPath}/${newPhotoPath}; // await RNFS.moveFile(result.assets[0].uri, newPath); setPhotoPath(result.assets[0].uri); // console.log("response is:", uri); const base64Image = result.assets[0].base64; // console.log('Error renaming photo:', base64Image); const source = { base64Image }; cloudinaryUpload(); } else { console.log('result.assets is undefined or empty.'); } } catch (error) { console.log('Error:', error); } } };

{
    return (
    <View>
        <Text>uploademp</Text>
    </View>
    )
}

}

export default uploademp I am still getting the same error, Kindly advice on a solution Regards, Derrick Presley

[image: Mailtrack] https://mailtrack.io?utm_source=gmail&utm_medium=signature&utm_campaign=signaturevirality11& Sender notified by Mailtrack https://mailtrack.io?utm_source=gmail&utm_medium=signature&utm_campaign=signaturevirality11& 08/21/23, 02:28:12 PM

On Mon, 21 Aug 2023 at 13:03, tamaracloudinary @.***> wrote:

In your code, you have to update the 'upload_preset' with your own, the cloud name with your own and import Cloudinary this way: import {Cloudinary} from @.***/url-gen';. Also, implement what happens inside the upload function. Please try these and let me know how it goes. Thanks,

  • Tamara

— Reply to this email directly, view it on GitHub https://github.com/cloudinary/cloudinary-react-native/issues/10#issuecomment-1686030645, or unsubscribe https://github.com/notifications/unsubscribe-auth/ASYXCJI2T3EJA3NEZUVLQEDXWMW6HANCNFSM6AAAAAA3PKNULA . You are receiving this because you authored the thread.Message ID: @.***>

tamaracloudinary commented 1 year ago

Hello,

Please proceed with the changes I suggested. Once you've done that, please let me know if the issue persists.

Best regards, Tamara

Presleyderrick commented 1 year ago

Hi,

I made the suggested changes please send me the code example perhaps there's something I am missing from mine. Just edit mine as it is and re-send it to me then I will let you know if it works.

Thanks.

Regards.

On Tue, Aug 22, 2023, 12:05 PM tamaracloudinary @.***> wrote:

Hello,

Please proceed with the changes I suggested. Once you've done that, please let me know if the issue persists.

Best regards, Tamara

— Reply to this email directly, view it on GitHub https://github.com/cloudinary/cloudinary-react-native/issues/10#issuecomment-1687780708, or unsubscribe https://github.com/notifications/unsubscribe-auth/ASYXCJNUR6AVHV5L77YEYCDXWRY6BANCNFSM6AAAAAA3PKNULA . You are receiving this because you authored the thread.Message ID: @.***>

tamaracloudinary commented 1 year ago

This is the relevant part you should change in your code:

import {Cloudinary} from '@cloudinary/url-gen';
import { launchCamera } from 'react-native-image-picker';

  const cld = new Cloudinary({
    cloud: {
      cloudName: 'dtauszhrv'
    },
    url: {
      secure: true
    }
  });

    const cloudinaryUpload = async () => {
            const options: UploadApiOptions = {
              upload_preset: 'e-permit',
              unsigned: true,

            }

    await upload(cld, {file: photoPath , options: options,callback: (error: any, response: any) => {
                    //.. handle response
                }})
        };
Presleyderrick commented 1 year ago

What should I change it to. The issue is with the upload line

On Tue, Aug 22, 2023, 2:59 PM tamaracloudinary @.***> wrote:

This is the relevant part you should change in your code:

`import {Cloudinary} from @.***/url-gen'; import { launchCamera } from 'react-native-image-picker';

const cld = new Cloudinary({ cloud: { cloudName: 'dtauszhrv' }, url: { secure: true } });

const cloudinaryUpload = async () => { const options: UploadApiOptions = { upload_preset: 'e-permit', unsigned: true,

    }

await upload(cld, {file: photoPath , options: options,callback: (error: any, response: any) => { //.. handle response }}) };

`

— Reply to this email directly, view it on GitHub https://github.com/cloudinary/cloudinary-react-native/issues/10#issuecomment-1688047683, or unsubscribe https://github.com/notifications/unsubscribe-auth/ASYXCJJXZFTOABA2R4OXQH3XWSNJZANCNFSM6AAAAAA3PKNULA . You are receiving this because you authored the thread.Message ID: @.***>

tamaracloudinary commented 1 year ago

You still didn't change your import to: import {Cloudinary} from '@cloudinary/url-gen';.

Presleyderrick commented 1 year ago

Hi,

This is my full code, If you can take a look at the other camera option it has imports for its options settings and launch settings,

please recheck the options for the upload since I am still having the same issue

import { PermissionsAndroid, Text, TouchableOpacity, View } from 'react-native' import React, { useState } from 'react' import {Cloudinary} from @.***/url-gen'; import { ImageLibraryOptions, launchCamera } from 'react-native-image-picker';

const cld = new Cloudinary({ cloud: { cloudName: 'dtauszhrv' }, url: { secure: true } });

const uploademp =()=> {
    const [photoPath, setPhotoPath] = useState<string | undefined>(

undefined);

    const cloudinaryUpload = async () => {
      const options: UploadApiOptions = {
        upload_preset: 'e-permit',
        unsigned: true,

      }

  await upload(cld, {file: photoPath , options: options,callback: (error

: any, response: any) => { if (error) { console.log("Error:", error); } else { console.log("Response:", response); } }}) };

  const imageoptions: ImageLibraryOptions = {
    mediaType: 'photo',
    maxWidth: 500,
    maxHeight: 500,
    includeBase64: true
  };
  const openCamera = async () => {
    const granted = await PermissionsAndroid.request(
         PermissionsAndroid.PERMISSIONS.CAMERA,
    );
    if (granted === PermissionsAndroid.RESULTS.GRANTED) {
    const result = await launchCamera(imageoptions);
              // const currentDate = new Date();
              // const formattedDate = format(currentDate,

'yyyyMMddHHmmss'); // const newPhotoPath = e_permit${formattedDate}.jpg;

      try {
            if (result && result.assets && result.assets[0]) {
                  // const newPath =

${RNFS.DocumentDirectoryPath}/${newPhotoPath}; // await RNFS.moveFile(result.assets[0].uri, newPath); setPhotoPath(result.assets[0].uri); // console.log("response is:", uri); const base64Image = result.assets[0].base64; // console.log('Error renaming photo:', base64Image); const source = { base64Image }; cloudinaryUpload(); } else { console.log('result.assets is undefined or empty.'); } } catch (error) { console.log('Error:', error); } } };

{
    return (
    <View>
        <Text>uploademp</Text>
        <TouchableOpacity onPress={openCamera}>
          <Text>Say cheese</Text>
        </TouchableOpacity>
    </View>
    )
}

}

export default uploademp

Attatched are images showing what error I am receiving. I am using a tsx file

[image: Mailtrack] https://mailtrack.io?utm_source=gmail&utm_medium=signature&utm_campaign=signaturevirality11& Sender notified by Mailtrack https://mailtrack.io?utm_source=gmail&utm_medium=signature&utm_campaign=signaturevirality11& 08/23/23, 08:07:45 AM

On Tue, 22 Aug 2023 at 15:48, tamaracloudinary @.***> wrote:

You still didn't change your import to: import {Cloudinary} from @.***/url-gen';.

— Reply to this email directly, view it on GitHub https://github.com/cloudinary/cloudinary-react-native/issues/10#issuecomment-1688121671, or unsubscribe https://github.com/notifications/unsubscribe-auth/ASYXCJKSCKAKLJCH6MZEMZDXWSTDXANCNFSM6AAAAAA3PKNULA . You are receiving this because you authored the thread.Message ID: @.***>

tamaracloudinary commented 1 year ago

Hi, the camera is not related to Cloudinary so we can't provide support for it, but your imports still don't include the right import for Cloudinary, please change them from:

import {Cloudinary} from ***@***.***/url-gen';

to:

import {Cloudinary} from '@cloudinary/url-gen';
Presleyderrick commented 1 year ago

The camera is just a reference, kindly check your mail for snapshots of the problems I'm facing and give a definitive solution, the import statement is correct as it is in your mail I have no issue with that. The problem is not with the cloudinary tag that works fine, my problem is with the UploadApiOptions and the upload from the await upload. How can I import them?? the images are the errors I receive the last image is how I've done my imports

cloudinary coudinary2

Import

Presleyderrick commented 1 year ago

I am using a tsx file not a ts. I tried it with the links provided but still same error

ericyliu commented 1 year ago

im having the same issue and confused as to where you are getting the upload method from the line await upload(cld, {file: photoPath , options: options,callback: (error: any, response: any) => {

The docs just don't make sense to me, and I am unable to figure out where upload is being imported from

edit after digging through this codebase, it seems like the upload method lives inside api/upload/src/uploader.tsx, but this package is not exposing it

edit2 after copying over the relevant files and trying to call the upload method, i'm now getting [TypeError: Network request failed] from this code:

const response = await new Promise<UploadApiResponse>((resolve, reject) =>
    upload(cloudinary, {
      file: base64String,
      options: {
        upload_preset: "xxxxxx",
        unsigned: true,
      },
      callback: (error, result) => {
        if (error) {
          console.log(error);
          return reject(error);
        }
        return resolve(result);
      },
    })
  );
  return response.secure_url;
};

edit3 @Presleyderrick gave up on this package for now and ended up using xhr to upload

const uploadFile = async (
  localAsset: ImagePickerAsset,
  journeyId: string,
  fileName: string
): Promise<string> => {
  if (localAsset.type === "video" && localAsset.duration > 60 * 1000) {
    alert("Video duration must be less than 1 minute.");
    throw new Error("Video duration too long.");
  }
  const apiUrl = `https://api.cloudinary.com/v1_1/{CLOUDINARY_ID}/${localAsset.type}/upload`;
  return new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest();
    xhr.open("POST", apiUrl);
    xhr.onload = () => {
      const res = JSON.parse(xhr.response);
      if (res.error) return reject(res.error);
      if (localAsset.type === "video") {
        const path = res.secure_url.split(
          "https://res.cloudinary.com/{CLOUDINARY_ID}/video/upload"
        )[1];
        return resolve(
          `https://res.cloudinary.com/{CLOUDINARY_ID}/video/upload/q_auto:good${path}`
        );
      }
      resolve(res.secure_url);
    };
    xhr.onerror = (error) => {
      reject(error);
    };
    xhr.ontimeout = (error) => {
      reject(`timeout: ${error}`);
    };
    const formData = new FormData();

    formData.append("file", {
      uri: localAsset.uri,
      type: localAsset.type === "video" ? "video/mp4" : "image/jpg",
      name: fileName,
    } as any);
    formData.append("upload_preset", "{UPLOAD_PRESET}");
    formData.append("folder", journeyId);
    formData.append("public_id", fileName);
    xhr.send(formData);
  });
};

credit to https://gist.github.com/nandorojo/7063a8d15bd3bb235949882f14674985

tamaracloudinary commented 1 year ago

Hi, I wanted to update you that a fix for the issue was deployed. Can you please try and let me know if everything works okay for you now? Thank you for your patience, and sorry about the late identification of the issue. Best, Tamara

joemewes commented 1 year ago

I have an issue related as well. It looks like upload should be imported from this library. ie. import { upload } from 'cloudinary-react-native'; as per https://github.com/cloudinary/cloudinary-react-native/blob/master/src/index.tsx.

but when imported we get this error

undefined Unable to resolve module ./../api/upload/model/params/upload-params

any suggestions?

tamaracloudinary commented 1 year ago

Hi @joemewes, Thank you for bringing this to our attention. The issue has been successfully resolved and deployed. Please upgrade to version 0.1.1.

Cheers!

Presleyderrick commented 1 year ago

Hi, so initially the package ran well but on the update to 0.1.1 now I get a

Could not find a declaration file for module 'cloudinary-react-native'. 'd:/Git_rip/gnovationEPERMIT/node_modules/cloudinary-react-native/lib/commonjs/index.js' implicitly has an 'any' type. Try npm i --save-dev @types/cloudinary-react-native if it exists or add a new declaration (.d.ts) file containing declare module 'cloudinary-react-native';ts(7016) image

tamaracloudinary commented 1 year ago

Hi @Presleyderrick, can you please check your package.json to make sure that the cloudinary-react-native exists and run npm install to make sure it’s installed? Please search the node_modules folder to make sure it’s there. Thanks, Tamara

Presleyderrick commented 1 year ago

I did install it, as you can see Import for cloudinary URL gen reads properly

tamaracloudinary commented 1 year ago

@Presleyderrick are you sure? can you please run a quick npm install to make sure it's installed? Looking forward to your update

Presleyderrick commented 1 year ago

Hi @tamaracloudinary, The image below is a snippet of my package.json file image

tamaracloudinary commented 1 year ago

Hi @Presleyderrick, In order to better understand the issue, I need some more information. Can I please ask you to provide more details about the problem you're encountering?

Presleyderrick commented 1 year ago

Hi @tamaracloudinary I can easily import import { Cloudinary } from "@cloudinary/url-gen";

But when I try to import import {AdvancedImage, upload} from 'cloudinary-react-native';

I get Could not find a declaration file for module 'cloudinary-react-native'. Try npm i --save-dev @types/cloudinary-react-native if it exists or add a new declaration (.d.ts) file containing declare module 'cloudinary-react-native';

as the Image below shows I am using a tsx file image

tamaracloudinary commented 1 year ago

Thanks @Presleyderrick, we released a new fixed version 0.1.2, can you please try it and let me know how it goes?

RiteshJariwala commented 1 year ago

I have the following code:

export const uploadImages = async () => { let files = ['/sdcard/Download/mrousavy1486082660270893213.jpg', '/sdcard/Download/mrousavy167616870848093416.jpg']; const cld = new CloudinaryRN({ cloud: { cloudName: cloudName, }, url: { secure: true, }, });

const options = { signature: signature, timestamp: timestamp, api_key: apiKey, }; await upload(cld, { file: files[0], options: options, callback: (error, response) => { //.. handle response console.log('response', response, error, index); }, }); }

I am getting the following errors and warnings:

ERROR Error: Cannot find native module 'ExpoCrypto', js engine: hermes

WARN Possible Unhandled Promise Rejection (id: 0): TypeError: Cannot read property 'process_request_params' of undefined TypeError: Cannot read property 'process_request_params' of undefined

I am having "cloudinary-react-native": "^0.1.2" installed

Any one here to help out?

momoip commented 1 year ago

Hi @RiteshJariwala We are checking with our Dev team and will respond shortly.

Presleyderrick commented 1 year ago

Hi @momoip is there any update?

singhayush1403 commented 1 year ago

My uploads are failing on android but working on iOS. any reason why?

dannyv-cloudinary commented 1 year ago

Hi @singhayush1403.

Could you please raise a support ticket with us including any code samples, stack traces, and error messages that may be relevant, so we can look into this in greater detail for you?

Many thanks! -Danny

naveenbhusare commented 8 months ago

@RiteshJariwala did you found solution for this i as well facing the same issue ?

momoip commented 8 months ago

Hi there, Thanks for letting us know.
I'm checking with our Dev team and will let you know.
Thanks, Mo

momoip commented 8 months ago

Hi there, We have found the fix that we need mimeType to the fetch request on Android. We have raised an internal ticket and will let you know when the fix is deployed. Thanks, Mo

momoip commented 7 months ago

Hi @singhayush1403, We have made the fix for Android. Please let us know if it works for you. Regards, Mo