GithubHelp home page GithubHelp logo

uploadcare / uploadcare-js-api-clients Goto Github PK

View Code? Open in Web Editor NEW
58.0 12.0 14.0 8.15 MB

JavaScript library for work with Uploadcare API

Home Page: https://uploadcare.com/docs/start/api/

License: MIT License

JavaScript 1.93% TypeScript 98.05% Shell 0.02%
uploadcare uploader upload store file files image images file-upload image-upload

uploadcare-js-api-clients's Introduction

Uploadcare JS API Clients

Uploadcare JavaScript/TypeScript API clients for Node.js and browsers. Handles uploads and further operations with files by wrapping Uploadcare Upload and REST APIs.

Build Status NPM version GitHub release  Uploadcare stack on StackShare

Packages

Security issues

If you think you ran into something in Uploadcare libraries that might have security implications, please hit us up at [email protected] or Hackerone.

We'll contact you personally in a short time to fix an issue through co-op and prior to any public disclosure.

Feedback

Issues and PRs are welcome. You can provide your feedback or drop us a support request at [email protected].

uploadcare-js-api-clients's People

Contributors

bautrukevich avatar dependabot[bot] avatar egordidenko avatar filippovam avatar foxeyes avatar github-actions[bot] avatar ikatsuba avatar jeetiss avatar kamillagarifullina avatar lgtm-com[bot] avatar nd0ut avatar renovate-bot avatar renovate[bot] avatar v-atamanenko avatar wreckah avatar zmoki avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

uploadcare-js-api-clients's Issues

Cannot create URL for blob!

Describe the bug

Cannot upload images via method UploadClient.uploadFile on android using Expo Go.
I get the following error:

"Cannot create URL for blob!"

When I try to upload an image to Uploadcare via the JS api client, it fails on android only

Expected behavior

The image 'test.jpg' is expected to be uploaded to ImageCare upon following code being executed:

Code / screenshots

import { UploadClient } from '@uploadcare/upload-client'

const client = new UploadClient({ publicKey: 'XXXXXXXXX',  })

// Uploads an image to UploadCare
export const uploadToUploadCare = async (blob: Blob, fileName: string) => {
	try {
		const fileRef = await client.uploadFile(blob, {
			fileName,
		})

		return fileRef.cdnUrl

	} catch (e) {
		console.warn(e)
		throw e
	}
}

// Grabs first image from gallery and calls uploadToUploadCare
const testUploader = async () => {
	try {
		const images = await MediaLibrary.getAssetsAsync({
			sortBy: 'creationTime',
			first: 1,
			mediaType: [MediaType.photo, ],
		})

		const img = await fetch(images.assets[0].uri)
		const blob = await img.blob()

		await uploadToUploadCare(blob, 'test.jpg')

	} catch (e) {
		alert(e)
	}
}

testUploader()

Environment

  • Library version:
    5.1.1

  • Language/framework version:
    expo: 46.0.0 (managed workflow)
    react-native: 0.69.6

  • OS version:
    Android 11 (OnePlus 6)

delete / delete-batch

I should be able to delete images via sdk¹

It's a little sad that i can only upload images via sdk, but have to use manual rest requests for everything else.
Would be good if i could at least delete & perhaps deleteBatch via sdk as it's supported, but just not implemented here: https://uploadcare.com/api-refs/rest-api/v0.5.0/#operation/deleteFileStorage.

My usecase would be uploading a users profile image - i want to delete the existing one and upload a new one.


In fact it would be good if things like, "list" would also be supported via sdk

Add react-native support

If you try to use this client to upload a file you will see the next error:

https://github.com/uploadcare/uploadcare-upload-client/blob/9abd0b059ce90e20e044d471625d55fa5e28527d/src/uploadFile/index.ts#L168

So, I have to use a hack to upload file

import defaultSettings from '@uploadcare/upload-client/lib/defaultSettings';
import upload from '@uploadcare/upload-client/lib/uploadFile';

const populateOptionsWithSettings = (options) => ({
  ...defaultSettings,
  publicKey: 'XXXXX',
  ...options,
});

export const uploadFile = ({ size, name, type, uri }, options) =>
  upload({ name, size, type, uri }, populateOptionsWithSettings(options));

How to stream upload a file with node?

How to stream upload a file with Node.js?

Hi, first of all thank you for your library.

Here's a quote of the type of the uploadFile function:

 uploadFile(
    data: NodeFile | BrowserFile | Url | Uuid,
    options: FileFromOptions
  ): Promise<UploadcareFile>

If I have a large file on disk and don't want to load it in memory, how could I do that? Because in the example the file data is already in RAM but I would like to avoid that.

Thanks and have a great day!

Add AWS Rekognition Moderation addon

API refs: https://uploadcare.com/api-refs/rest-api/v0.7.0/#tag/Add-Ons/operation/awsRekognitionDetectModerationLabelsExecute

We have two methods: executeAddon and addonExecutionStatus. They're accepting addon name as an option. So looks like we need to just add aws_rekognition_detect_moderation_labels here: https://github.com/uploadcare/uploadcare-js-api-clients/blob/92c4228014d1753cf48f485b792daff0964da0f7/packages/rest-client/src/types/AddonName.ts#

Also we need to add result types for the file info (see https://uploadcare.com/api-refs/rest-api/v0.7.0/#tag/File/operation/fileInfo app_data/aws_rekognition_detect_moderation_labels)

Library Launch Roadmap

Target: launch a production-ready package

Stages

Alpha 0

  • Support of following Uploadcare Settings:
    • publicKey,
    • baseUrl,
    • doNotStore,
    • integration,
    • userAgent,
    • secureExpire,
    • secureSignature
  • The request function to request to any path of Upload API
    • with the support of Uploadcare Settings
  • A function to run upload request to Upload API, with progress and cancel, with the support of Uploadcare Settings
  • Exporting both UploadcareUpload class and individual functions (useful for tree shaking)
  • Set up Uploadcare Settings as function‘s parameter and as in constructor and special method of UploadcareUpload class for changing settings in any way
  • Wrappers for following paths of Upload API: base, info
  • The high-level function like filesFrom only with the support of direct uploads (base) yet

Alpha 1

  • Use package version in getUserAgent
  • Add on/off methods Make uploading thenable

Alpha 2

  • The support of url uploads in fileFrom
  • Low-level request wrappers for /from_url/ and /from_url/status/ paths of Upload API.
  • Settings: the support of setting baseCDN, checkForUrlDuplicates, saveUrlForRecurrentUploads.

Alpha 3

  • Add support of upload file from uploaded in fileFrom
  • Add throttling to API requests

Alpha 4

  • Wrappers for group paths of Upload API
  • Add uploading progress for Node.js in base method
  • The high-level function for group uploading, aka filesGroupFrom

Coming up

Alpha 5

  • Support of multipart and uploading of big files

Alpha 6

  • Use user feedback from alpha program
  • Support of next following Uploadcare Settings: pusherKey (?), debug
  • Contribution guide

Next, we will fix bugs, structure, and naming, if needed, and prepare the library for production release.

Error while importing uploadcare modules

I have encountered the exact same error attempting to import the UploadClient module as well as the @uploadcare/react-widget module.

My stack is node.js 14LTS with React over next.js.

I have attempted to import using a standard import statement, import() function, as well as next/dynamic. Each behaves the same way and results in a similar stack with the same error message.

Interestingly enough, this fails:

import {UploadClient} from "@uploadcare/upload-client";

But this works:

import {UploadClient} from "../../../../node_modules/@uploadcare/upload-client/dist/index.node";

I can't use the 2nd method, for obvious reasons, but it seems like the importer is choosing the wrong file to import for some reason.

My package.json:

{
  "name": "sim",
  "version": "1.0.0",
  "description": "",
  "main": "src/server.mjs",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "build": "next build",
    "start": "node src/server.mjs",
    "dev": "nodemon src/server.mjs -e json,js,cjs,mjs",
    "remoteDev": "nodemon -- --inspect=0.0.0.0:9229 src/server.mjs -e json,js,cjs,mjs"
  },
  "author": "Ronald Barbosa <[email protected]>",
  "license": "UNLICENSED",
  "dependencies": {
    "@omarmfs98/nextjs-orgchart": "^1.0.8",
    "@sendgrid/mail": "^7.6.2",
    "@uploadcare/react-widget": "^2.2.0",
    "@uploadcare/upload-client": "^5.1.0",
    "ajv": "^8.11.0",
    "axios": "^0.21.4",
    "bcrypt": "^5.0.1",
    "copy-webpack-plugin": "^10.2.4",
    "formidable": "^2.0.1",
    "graphql": "^15.5.1",
    "iron-session": "^6.1.3",
    "mongo-sanitize": "^1.1.0",
    "mongoose": "^5.13.0",
    "next": "^11.0.1",
    "next-connect": "^0.12.2",
    "next-routes": "^1.4.2",
    "qrcode": "^1.5.0",
    "react": "^17.0.2",
    "react-dom": "^17.0.2",
    "semantic-ui-css": "^2.4.1",
    "semantic-ui-react": "^2.0.3",
    "speakeasy": "^2.0.0",
    "tesseract.js": "^2.1.5",
    "validator": "^13.7.0"
  },
  "devDependencies": {
    "nodemon": "^2.0.8"
  }
}

The stack is shown here:

Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: /com.omnivertical.apps/sim/node_modules/@uploadcare/upload-client/dist/index.node.js
require() of ES modules is not supported.
require() of /com.omnivertical.apps/sim/node_modules/@uploadcare/upload-client/dist/index.node.js from /com.omnivertical.apps/sim/.next/server/pages/api/passport/create.js is an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which defines all .js files in that package scope as ES modules.
Instead rename index.node.js to end in .cjs, change the requiring code to use import(), or remove "type": "module" from /com.omnivertical.apps/sim/node_modules/@uploadcare/upload-client/package.json.

    at new NodeError (<node_internals>/internal/errors.js:322:7)
    at Object.Module._extensions..js (<node_internals>/internal/modules/cjs/loader.js:1102:13)
    at Module.load (<node_internals>/internal/modules/cjs/loader.js:950:32)
    at Function.Module._load (<node_internals>/internal/modules/cjs/loader.js:790:12)
    at Module.require (<node_internals>/internal/modules/cjs/loader.js:974:19)
    at require (<node_internals>/internal/modules/cjs/helpers.js:101:18)
    at Object.@uploadcare/upload-client (/com.omnivertical.apps/sim/.next/server/pages/api/passport/create.js:132:18)
    at __webpack_require__ (/com.omnivertical.apps/sim/.next/server/webpack-runtime.js:33:42)
    at eval (webpack-internal:///./src/pages/api/passport/create.js:12:83)
    at Object../src/pages/api/passport/create.js (/com.omnivertical.apps/sim/.next/server/pages/api/passport/create.js:88:1)
    at __webpack_require__ (/com.omnivertical.apps/sim/.next/server/webpack-runtime.js:33:42)
    at __webpack_exec__ (/com.omnivertical.apps/sim/.next/server/pages/api/passport/create.js:230:52)
    at /com.omnivertical.apps/sim/.next/server/pages/api/passport/create.js:231:28
    at Object.<anonymous> (/com.omnivertical.apps/sim/.next/server/pages/api/passport/create.js:234:3)
    at Module._compile (<node_internals>/internal/modules/cjs/loader.js:1085:14)
    at Object.Module._extensions..js (<node_internals>/internal/modules/cjs/loader.js:1114:10)

Running into `TypeError: source.on is not a function` when using Sveltekit

Describe the bug

👋🏽 I'm running into a reproducible issue. Hopefully this is just me missing something simple.

I'm seeing an exception TypeError: source.on is not a function when trying to save an image in a Sveltekit project. Full trace:

TypeError: source.on is not a function
    at DelayedStream.create (...\node_modules\delayed-stream\lib\delayed_stream.js:33:10)
    at CombinedStream.append (...\node_modules\combined-stream\lib\combined_stream.js:45:37)
    at FormData.append (...\node_modules\form-data\lib\form_data.js:75:3)
    at buildFormData (.../node_modules/@uploadcare/upload-client/dist/esm/index.node.mjs:383:18)
    at retryIfFailed.retryNetworkErrorMaxTimes.retryNetworkErrorMaxTimes (.../node_modules/@uploadcare/upload-client/dist/esm/index.node.mjs:520:15)
    at .../node_modules/@uploadcare/upload-client/dist/esm/index.node.mjs:464:44
    at runAttempt (.../@uploadcare/upload-client/dist/esm/index.node.mjs:91:16)
    at retrier (.../node_modules/@uploadcare/upload-client/dist/esm/index.node.mjs:96:12)
    at retryIfFailed (.../node_modules/@uploadcare/upload-client/dist/esm/index.node.mjs:464:12)
    at base (.../node_modules/@uploadcare/upload-client/dist/esm/index.node.mjs:512:12)
  1. Initialize a Sveltekit project as described: https://kit.svelte.dev/docs/creating-a-project
  2. Create a simple +page.svelte file:
<form method="POST" enctype="multipart/form-data">
    <input type="file" name="file" />
    <button type="submit">Submit</button>
</form>
  1. Wire up a +page.server.js file:
import { uploadFile } from '@uploadcare/upload-client';
import { UPLOADCARE_API_KEY } from '$env/static/private';

export const actions = {
    default: async({request}) => {
        let formData = await request.formData();
        let file = formData.get('file');
        await uploadFile(file, {
			publicKey: UPLOADCARE_API_KEY,
		});
    }
}

Expected behavior

A successful file upload.

Code / screenshots

I don't have a small, self-contained example, but I do have a repo that recreates the issue: https://github.com/plattegruber/uploadcare-sveltekit-recreation

You can clone and open in a codespace, and run npm run dev -- --open.

Environment

  • Library version: 6.14.1
  • Language/framework version:
  • OS version:

Dependency Dashboard

This issue provides visibility into Renovate updates and their statuses. Learn more

Awaiting Schedule

These updates are awaiting their schedule. Click on a checkbox to get an update now.

  • chore(deps): update actions/github-script action to v5
  • chore(deps): update actions/setup-node action to v2
  • chore(deps): update dependency @types/node to v16
  • chore(deps): update dependency data-uri-to-buffer to v4
  • chore(deps): update dependency eslint to v8
  • chore(deps): update dependency eslint-plugin-prettier to v4
  • chore(deps): update typescript-eslint monorepo to v5 (major) (@typescript-eslint/eslint-plugin, @typescript-eslint/parser)

Open

These updates have all been created already. Click a checkbox below to force a retry/rebase of any.


  • Check this box to trigger a request for Renovate to run again on this repository

Type import broken with TS nodenext

Describe the bug

Could not find a declaration file for module '@uploadcare/upload-client'.

I guess, it might be caused by the types being defined like this in upload-client/package.json

  "types": "./dist/types.d.ts",
  "exports": {
    ".": {
      "node": "./dist/index.node.js",
      "browser": "./dist/index.browser.js",
      "default": "./dist/index.browser.js"
    }
  }

This is not valid in TS' ESM-support mode (NodeNext). The types field is only used for legacy projects. New TS > 4.7 projects with nodenext mode expect the types to be at ./dist/index.d.ts.

In case you want to leave the types at their current location, you additionally need to add the types definition within the exports block, as described here:
https://www.typescriptlang.org/docs/handbook/release-notes/typescript-4-7.html#packagejson-exports-imports-and-self-referencing

Also important:

Note that the "types" condition should always come first in "exports".

Expected behavior

TS type imports should work in TS >= 4.7 & NodeNext mode. I assume you intend to support NodeNext, as you moved the package to ESM-only anyway.

Code / screenshots

Environment

  • Library version: 5.1.0
  • Language/framework version: Node.js v16.18.0 & TS: 4.8.4

Preview image

When I upload an image, the widget says the name and the file size. If I click here, it preview my image and says "Add this image?". Why??? It's already added!! It doesn't do anything if I click "add" or "cancel"

How to add file name when calling uploadFileGroup?

Question

When uploading an array of images by url, how to add custom metadata do each image, like file name, tags, labels?

import {uploadFileGroup} from '@uploadcare/upload-client'

const urls = [
  'https://example.com/903948384271/image.png',
  'https://example.com/903948384282/image.png',
  'https://example.com/903948384293/image.png',
  'https://example.com/903948384302/image.png',
  'https://example.com/903948384313/image.png',
]

const {files} = await uploadFileGroup(urls, {
  publicKey: 'uploadCarePublicKey',
  store: 'auto',
  checkForUrlDuplicates: true,
  secureSignature: 'secureSignature',
  secureExpire: 'secureExpire',
  maxConcurrentRequests: 10,
  saveUrlForRecurrentUploads: true
})
// RESULT
files = [
  {
    mimeType: 'image/jpeg',
    name: 'image.png',
    originalFilename: 'image.png',
  },
  {
    mimeType: 'image/jpeg',
    name: 'image.png',
    originalFilename: 'image.png',
  },
  {
    mimeType: 'image/jpeg',
    name: 'image.png',
    originalFilename: 'image.png',
  },
  {
    mimeType: 'image/jpeg',
    name: 'image.png',
    originalFilename: 'image.png',
  },
  {
    mimeType: 'image/jpeg',
    name: 'image.png',
    originalFilename: 'image.png',
  },
]

React Native Issue uploading smaller files

I have added this library to my ReactNative project. It works great for larger file sizes but trying to use it for smaller files doesn't seem to be working.

I get the following error when trying to upload smaller files:

UploadClientError: [400] Request does not contain files.

This works fine with 3-minute videos, I have no issues with it at all.

This is the code I am using to upload the files:

import UploadClient from '@uploadcare/upload-client'

const client = new UploadClient({ publicKey: 'XXX' })

const resp = await fetch(image.uri);
const blob = await resp.blob();
const uriParts = image.uri.split('.');
const ext = uriParts[uriParts.length - 1];
const filename = `file.${ext}`;

const uploadResponse = await client.uploadFile(blob, { fileName: filename });

Expo CLI 4.1.4 environment info:
System:
OS: macOS 10.15.7
Shell: 5.7.1 - /bin/zsh
Binaries:
Node: 12.16.3 - /usr/local/bin/node
Yarn: 1.22.4 - /usr/local/bin/yarn
npm: 6.14.4 - /usr/local/bin/npm
SDKs:
iOS SDK:
Platforms: iOS 14.4, DriverKit 20.2, macOS 11.1, tvOS 14.3, watchOS 7.2
IDEs:
Android Studio: 3.6 AI-192.7142.36.36.6392135
Xcode: 12.4/12D4e - /usr/bin/xcodebuild
npmPackages:
expo: ^40.0.1 => 40.0.1
react: 16.13.1 => 16.13.1
react-dom: 16.13.1 => 16.13.1
react-native: https://github.com/expo/react-native/archive/sdk-40.0.1.tar.gz => 0.63.2
react-native-web: ~0.13.12 => 0.13.14
npmGlobalPackages:
expo-cli: 4.1.4
Expo Workflow: managed

ReferenceError: window is not defined in node v12.10.0

node --version
v12.10.0

/Users/jeetiss/Projects/uploadcare-upload-client/dist/uploadcare-upload-client.js:1557
    var browser = typeof self == 'object' ? self.FormData : window.FormData;
                                                            ^

ReferenceError: window is not defined
    at /Users/jeetiss/Projects/uploadcare-upload-client/dist/uploadcare-upload-client.js:1557:61
    at /Users/jeetiss/Projects/uploadcare-upload-client/dist/uploadcare-upload-client.js:9:68
    at Object.<anonymous> (/Users/jeetiss/Projects/uploadcare-upload-client/dist/uploadcare-upload-client.js:12:2)
    at Module._compile (internal/modules/cjs/loader.js:936:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:947:10)
    at Module.load (internal/modules/cjs/loader.js:790:32)
    at Function.Module._load (internal/modules/cjs/loader.js:703:12)
    at Module.require (internal/modules/cjs/loader.js:830:19)
    at require (internal/modules/cjs/helpers.js:68:18)


Release 1.1.0

Release 1.1.0

uploadFromUrl Release

  • added sockets to uploadFromUrl
  • fixed some bugs

Unable to Import UploadClient

Describe the bug

I am not even able to import UploadClient, as whenever I do I receive an error saying that UploadClient has no main function to use, thus the entire package is useless and errors out

  1. install @uploadcare/upload-client
  2. Import UploadClient

Expected behavior

Error: InternalError Metro has encountered an error: While trying to resolve module @uploadcare/upload-client from file /Users/nickfatherbool/Documents/GitHub/the-tom-app-native/Global/Camera.js, the package /Users/nickfatherbool/Documents/GitHub/the-tom-app-native/node_modules/@uploadcare/upload-client/package.json was successfully found. However, this package itself specifies a main module field that could not be resolved (/Users/nickfatherbool/Documents/GitHub/the-tom-app-native/node_modules/@uploadcare/upload-client/dist/index.browser.cjs. Indeed, none of these files exist:

Code / screenshots

Environment

  • Library version:
  • Language/framework version:
  • OS version:

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.