Git Product home page Git Product logo

cloudinary_js's Introduction

Cloudinary Javascript SDKs (Legacy)

Note About Legacy SDKs

While these SDKs still work, we recommend using the new @cloudinary/url-gen package instead. You can read it's documentation here.

About

The Cloudinary Javascript SDK allows you to quickly and easily integrate your application with Cloudinary. Effortlessly optimize, transform, and upload your cloud's assets.

This repository is the home for three distinct packages

Contributions

  • Ensure tests run locally (npm run test)
  • Open a PR and ensure Travis tests pass

Get Help

If you run into an issue or have a question, you can either:

About Cloudinary

Cloudinary is a powerful media API for websites and mobile apps alike, Cloudinary enables developers to efficiently manage, transform, optimize, and deliver images and videos through multiple CDNs. Ultimately, viewers enjoy responsive and personalized visual-media experiences—irrespective of the viewing device.

Additional Resources

Licence

Released under the MIT license.

cloudinary_js's People

Contributors

asisayag2 avatar cloudinary-jenkins avatar crazile avatar dependabot[bot] avatar digitaltoad avatar echatzief avatar eitanp461 avatar eroh92 avatar ethul avatar gotik avatar gvillenave avatar ignatiusreza avatar itaibenari avatar m0she avatar maxim-filimonov avatar meirfeinberg avatar nadavofi avatar nadavs avatar nirmaoz avatar patrick-tolosa avatar seba-1511 avatar shedar avatar snyk-bot avatar strausr avatar tallevami avatar tocker avatar yakirp avatar yomesinc avatar yuval-cloudinary avatar zvictor 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  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  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

cloudinary_js's Issues

$.cloudinary.image with width="auto" does not set the data-src attribute

I read on this cloudinary's blog article that the SDKs would handle the width="auto" param and return an image with a blank src attribute and the data-src attribute set to the url to be used when calling $.cloudinary.responsive() but the img tag I get does not contain the data-src attribute.

Instead, the image function sets data("src-cache") (as of cloudinary_js 1.0.25)

    image: function(public_id, options) {
      options = $.extend({}, options);
      var url = prepare_html_url(public_id, options);
      var img = $('<img/>').data('src-cache', url).attr(options).cloudinary_update(options);
      return img;
    },

This prevents $.cloudinary.responsive() to work.

Am I doing something wrong or is this a bug ?

Thanks.

original filename / public_id

Can you include original filename in json returned by the server? Or, is there an option to use original filename as public_id?

Superfluous headers

The part of the cloudinary file upload javascript that uses headers: { "X-Requested-With": "XMLHttpRequest" } seems redundant. The request is already sent via ajax via fileupload so why does Cloudinary reject the request if those headers aren't present?

Missing tag after fixing bower.json syntax error

Thank you very much for fixing the syntax error with bower.json -> 064fb90

With the following part, I still get this syntax error via 'bower install':

"cloudinary": "https://github.com/cloudinary/cloudinary_js.git",

I suggest creating a new release (1.0.14) for this. Forking and tagging help me fixing this issue.

Kind regards
winterstefan

Uploading on mobile device needs smaller cloudinary_js

Yeah, My website has used cloudinary for a long time on pc and we paid for better bandwidth.

But we are working on mobile web pages right now which requires image upload function too. And the cloudinary_js requires jquery image upload stuff which is really huge to load.

I am just wondering if you nice guys could supply a version of cloudnary_js supported by zepto.js?

hard fileupload dependency introduced in 2.0.2

This commit 7b9ee40 introduces a hard dependency on the fileupload plugin. When it's not included, it crashes.
For the user app we are using cloudinary only for displaying of images, so we don't need the fileupload.
As a bonus it would be nice if there was a smaller build which doesn't include the uploading capabilities at all.

this.fileupload is not a function

2.0.1 works for me, but on 2.0.3 I get a runtime error of Uncaught TypeError: this.fileupload is not a function.

Error occurs at line 3307 of cloudinary-jquery-file-upload/cloudinary-jquery-file-upload.js.
screenshot 2015-11-30 03 31 09

Cloudinary Upload Widget messing up button's text when using custom stylesheet

Here is an example scenario:
Let's say we have a button. Once this button is clicked, the widget is open.

$('#btn-upload-sample').on('click', function() {
    ...
    cloudinary.openUploadWidget(options, function(error, result) {...}
}

Let's say we've configured the widget with the following settings:

var options = {
    cloud_name: "foo",
    upload_preset: "whatever",
    multiple: false,
    text: {
        'sources.local.select_file' : "Choose a file..."
    }
};

Since we defined multiple: false, inside the widget's modal, the "Select File" button's text should reflect the parameter sources.local.select_file that we've set. When the widget is opened, the button displays "Choose a file..." as it should. Everything is ok so far.

But if we add any custom stylesheet to our widget (let's say it can be found at //yourdomain.com/assets/css/cloudinary-widget.min.css)

var options = {
    cloud_name: "foo",
    upload_preset: "whatever",
    multiple: false,
    text: {
        'sources.local.select_file' : "Choose a file..."
    },
    stylesheet: "//yourdomain.com/assets/css/cloudinary-widget.min.css"
};

and then refresh the page and open the widget again, the same button displays "Select files" (or whatever we put on sources.local.select_files in text parameter).

It seems that when we have a custom stylesheet, the widget ignores the multiple parameter when it's deciding which text should be inside the button, the "single" or "multiple" one. The upload itself is not affected btw, only the text.

Best regards.

Cannot set tags against uploads

Using the .config() method I set the tags, but they're not being attached to the uploaded images.

$.cloudinary.config({ tags: "awesometag" });

Am I setting the tags in the incorrect place?

Documentation Needed on How to upload from text input using URL

Using the plugin works easily enough when setting up a type=file input field, but I can't figure out how to get it to work using website URL.

I tried

$('#url_field').cloudinary_fileupload();

but nothing happens. Can you please provide some documentation on how to use the jquery plugin with a URL rather than a file input?

Impossible to specify additional params on JavaScript

Hi,

When uploading from JavaScript we want to specify public_id option as per the documentation.

So I do it by setting formData on upload start:

          fileUpload.bind("fileuploadsubmit", function(e, data) {
            debugger;
            var formData = $(this).fileupload('option').formData;
            data.formData = $.extend({public_id: 'foo'}, formData); // 'foo' will be actual file name that is being uploaded
            return true;
          })

But the problem is that when doing so on the client-side, the signature parameter is no longer valid (because we added additional public_id parameter).
The cloudinary, of course, responds with 401 Unauthorized when trying to upload.

Also the signature cannot be re-generated on the client side (we don't have api_secret on the client).

All it means is basically that there is no way to provide additional params from the JavaScript because any of those will render the signature invalid.

This contradicts to the documentation which must mean that I'm missing something.

Could you please suggest on this?

Thanks.

NPM package?

I'm currently using npm to manage my project's dependencies.

All of this projects dependencies have an NPM repo, why doesn't this project have an npm repo?

Java direct upload BAD REQUEST error

I used Java for building Image upload tag:

Map options = ObjectUtils.asMap("resource_type", "auto");
options.put("callback", "http://localhost:8080/cloudinary_cors.html");
Map htmlOptions = null;
String html = cloudinary.uploader().imageUploadTag("image_id", options, htmlOptions);

Put this String to Model attribute and show on page. Looks like result.
Picked some image and jquery.fileupload tried to send this image to Cloudinary.
I took Status Code: 400 Bad Request and response:

error: {message: "Upload preset must be specified when using unsigned upload"}

All of my settings is right, I can send image from server side, using this code:

Map uploadResult = cloudinary.uploader().upload("image.jpg", ObjectUtils.emptyMap())

but I can't send file from client side.
Code of page:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <script th:src="@{/js/common/jquery-1.11.3.min.js}" type="text/javascript"/>
    <script th:src="@{/js/cloudinary/jquery.ui.widget.js}" type="text/javascript"/>
    <script th:src="@{/js/cloudinary/jquery.iframe-transport.js}" type="text/javascript"/>
    <script th:src="@{/js/cloudinary/jquery.fileupload.js}" type="text/javascript"/>
    <script th:src="@{/js/cloudinary/jquery.cloudinary.js}" type="text/javascript"/>
</head>
<body>
    <span th:utext="${cloudyURL}" th:remove="tag"></span>
    <!-- config CloudinaryApi -->
    <script th:inline="javascript">
          $.cloudinary.config({"cloud_name":"CLOUDNAME", "api_key":"APIKEY"});
    </script>
</body>
</html>

I read all of your manuals, github issues, stackoverflow answers but can't force working direct upload.
Please help me, deal with this problem.

Lodash is now a dependency too?

I'm doing file uploads from the client. I have to include jQuery as a dependency, which I understand is being removed eventually.

In the meantime I'm maintaining my app and updating bower, and including the libraries as suggested:

  './src/bower_components/cloudinary-core/cloudinary-core.js'
  './src/bower_components/cloudinary-jquery/cloudinary-jquery.js'
  './src/bower_components/cloudinary-jquery-file-upload/cloudinary-jquery-file-upload.js'

I get Uncaught ReferenceError: _ is not defined

Adding lodash in front of them solves this.

Does this mean that the file upload is now dependent on lodash and jQuery both? Or am I missing something and there is a way around this?

Also as feedback, our team would strongly prefer that the cloudinary libraries be fully independent of external libraries.

Unable to upload file using AngularJS

I tried to upload file using ngFileUpload module and POST it to cloudinary server (Direct upload from client Side). I enabled unsigned upload from the Cloudinary console and used the upload_preset in the code. I can see the event happening but POST throws and error, "Upload preset must be specified when using unsigned upload". 400 (Bad Request)

    $scope.upload_cloudinary = function(files){
        //console.log($scope.$watch);
        console.log("Cloud Name: "+$.cloudinary.config().cloud_name+"Upload Preset: "+$.cloudinary.config().upload_preset);
        console.log();
        if(files && files.length){
            for(var i =0; i<files.length; i++){
                var file = files[i];
                Upload.upload({
                    url: "https://api.cloudinary.com/v1_1/" + $.cloudinary.config().cloud_name + "/upload",
                    data: {upload_preset: $.cloudinary.config().upload_preset, tags: 'UserProfilePics', context:'ProfilePics=' + $scope.title},
                    file:file
                }).progress(function(e){
                    //console.log(evt);
                    file.progress = Math.round((e.loaded * 100.0) / e.total);
                    console.log("Uploading... " + file.progress + "%");
                }).success(function(data, status, headers, config){
                    console.log(data, status, headers, config);
                });
            }
        }
        else{
            $bootbox.alert("No Image selected! You shall be grounded! >(");
        }
    }; 

No default for crop option in $.cloudinary.url()

The transformation documentation indicates that 'scale' is the default crop mode. Crafting urls directly, this is shown to be accurate: using w_500 yields an identical result to w_500,c_scale.

I expect the javascript library to work the same way: it seems to me the following calls should result in different urls, but identical images:

$.cloudinary.url( public_id, { width: 500 } )
// expected: http://res.cloudinary.com/demo/image/upload/w_500/public_id.jpg
// actual: http://res.cloudinary.com/demo/image/upload/public_id.jpg ! No transformation !

$.cloudinary.url( public_id, { width: 500, crop: 'scale' } )
// http://res.cloudinary.com/demo/image/upload/w_500,c_scale/public_id.jpg

This unexpected behavior is due to the following code in process_html_dimensions(options)

if (!crop && !has_layer) {
      delete options.width;
      delete options.height;
}

I don't see any reason for deleting the requested width and height transformations in the absence of an explicit crop option, nor any documentation for the resulting surprising behavior. Is there some edge case that would be damaged by removing this code?

Why based on jQuery?

Basing this library on jQuery has the big disadvantage of making it difficult to use on the server side in nodejs. Also, the nodejs library is not possible to run in the browser due to the use of node-only modules such as fs.

To me, it's not really clear why the jQuery requirement is needed?

A vanilla javascript library instead of one strict client-side and one strict server-side would be awesome.

Unable to upload when using Jquery Mobile

If I use Jquery Mobile in my web application, I get this error when I add a file and the upload is supposed to start:

Uncaught NotFoundError: Failed to execute 'replaceChild' on 'Node': The node to be replaced is not a child of this node.

the cloudinary code is very basic

$('.cloudinary-fileupload').cloudinary_fileupload({
    start : function(e) {
        console.log("upload start");
    },
    fail : function(e, data) {
        console.log("upload failed");
    }
});

Everything works fine without jquery mobile.
Any hints?

Error: Call to undefined function cl_image_upload_tag() in element

I'm trying to use this code inside of a CakePHP (latest version) element. And I'm having some issues (see the error below).

Error: Call to undefined function cl_image_upload_tag() 

You can see the full element code at [https://gist.github.com/robksawyer/4a95a0f6c11f71df432f].

I've also added the following to bootstrap.php and cl_image_tag is working in the views.

/**
 * Cloudinary CDN Setup
 */
App::import('Vendor', 'Cloudinary/Cloudinary.php');
App::import('Vendor', 'Cloudinary/Uploader.php');
App::import('Vendor', 'Cloudinary/Api.php');

$cloudinaryURL = parse_url(getenv('CLOUDINARY_URL'));
define('CLOUD_NAME', $cloudinaryURL['host']);
Cloudinary::config(array( 
    "cloud_name" => $cloudinaryURL['host'], 
    "api_key" => $cloudinaryURL['user'], 
    "api_secret" => $cloudinaryURL['pass']
));
/**
 * End Cloudinary CDN Setup
 */

Any ideas?

URL prefix when window.location.protocol is file:

hi,

I ran into an issue where I am loading the HTML page with the file:// protocol and would like call the cloudinary_url function to get the URL of the image file having the https:// protocol.

From the code, it looks like the secure option is ignored when the window.location.protocol is file:.

Would you consider instead, make the secure option overwrite that prefix to https:// no matter what value the window.location.protocol has? For example, that line could be something like:

var prefix = secure ? 'https://' : (window.location.protocol === 'file:' ? "file://" : 'http://');

Thanks!

Issue with JQuery Sortable and cloudinary_js

Hi has anyone reported an issue with jquery sortables and cloudinary_js.

I get the following error in jquery when i have the following sortable code running.

$('#goals').sortable({
  axis: 'y',
  dropOnEmpty: false,
  handle: '.handle',
  cursor: 'crosshair',
  items: '.nested_fields',
  opacity: 0.4,
  scroll: true
})

this is using:

jQuery UI - v1.9.0 - 2012-10-15
jQuery v1.7.2

jquery.ui.min.js:7

Uncaught TypeError: Object function ( name, base, prototype ) {
var namespace = name.split( "." )[ 0 ],
fullName;
name = name.split( "." )[ 1 ];
fullName = namespace + "-" + name;

if ( !prototype ) {
    prototype = base;
    base = $.Widget;
}

// create selector for plugin
$.expr[ ":" ][ fullName ] = function( elem ) {
    return !!$.data( elem, name );
};

$[ namespace ] = $[ namespace ] || {};
$[ namespace ][ name ] = function( options, element ) {
    // allow instantiation without initializing for simple inheritance
    if ( arguments.length ) {
        this._createWidget( options, element );
    }
};

var basePrototype = new base();
// we need to make the options hash a property directly on the new instance
// otherwise we'll modify the options hash on the prototype that we're
// inheriting from

// $.each( basePrototype, function( key, val ) {
// if ( $.isPlainObject(val) ) {
// basePrototype[ key ] = $.extend( {}, val );
// }
// });
basePrototype.options = $.extend( true, {}, basePrototype.options );
$[ namespace ][ name ].prototype = $.extend( true, basePrototype, {
namespace: namespace,
widgetName: name,
widgetEventPrefix: $[ namespace ][ name ].prototype.widgetEventPrefix || name,
widgetBaseClass: fullName
}, prototype );

$.widget.bridge( name, $[ namespace ][ name ] );

} has no method 'extend'

Make classname to activate 'responsive images' configurable

Currently the classname to apply the 'responsive' functionality is hard-coded to cld-responsive. "Why?" was the first thing that popped in to mind. Why not make it configurable while having a default value of cld-responsive?

This makes the Cloudinary library less obtrusive and therefore better adoptable. For examples, all our responsive images already have assigned a classname responsive which can then be 'reused'.

Use automatic dpr in background images

Hi

I'm using automatic dpr for my regular image tags and that works great. However, in some places I have images set as backgrounds of a div.
Does the cloudinary library have support for this use case as well?

Same public_id gets assigned to many images on multiple uploads

I'm trying to do multiple uploads to the Cloudinary API, but they all seem to get the same public_id.

I uploaded 8 images and in my Chrome Developer Console I see 9 requests in my Network tab (1 head and 8 post requests).

All the post requests look the same to me (except for the file field). The signature, timestamp and public api key are the same.

The response for 7 out of the 8 post requests are also identical. 7 of the images get the same public id (amgfphycgixuuihodxg9) and the last one gets a unique one b4yhpxzizprgokm3xivy.

This is my HTML for the upload images-button:

<input
  accept="image/jpeg,image/png"
  class="cloudinary-fileupload"
  data-cloudinary-field="image_management_batch_upload[image_ids]"
  data-form-data="{ ... }"
  data-url="https://api.cloudinary.com/v1_1/skalar-tt/auto/upload"
  multiple="multiple"
  name="file"
  type="file">

I'm not using any custom js.

width and height options are not included in src

    $.cloudinary.url(image_id, {width: 10, height: 10})

yields

http://res.cloudinary.com/cloud_name/image/upload/image_id.png

The same is true for $.cloudinary.image. The src does not include the width and height properties.

Can you please increment version of cloudinary gem? My pull request still isn't coming through.

Hi -

I recently submitted a pull request into cloudinary_js that was accepted.

However, in my project, the cloudinary gem that installs the javascript still has the old version even after I do bundle update.

Even if I erase the gem directory from my local machine and reinstall, I can't do that when I push to Heroku.

Can you please help me? I'd really like to get my updates into production. Thanks!

Trouble uploading unsigned via new jquery-file-upload

I'm trying to do an unsigned upload that was working fine with the previous version of file upload, but now I can't seem to get it configured. Trying to cobble together from the docs here http://cloudinary.com/documentation/jquery_image_upload

HTML

<script src="bower_components/jquery/dist/jquery.js"></script>
<script src="bower_components/cloudinary-jquery-file-upload/cloudinary-jquery-file-upload.js"></script>
...
<input type="file" name="file" class="cloudinary-fileupload" 
  data-form-data="%7B%22upload_preset%22:%22logo_260x60%22,%22cloud_name%22:%22mysite%22,%22tags%22:%22browser_uploads%22%7D"/>

JS

$.cloudinary.config({ cloud_name: 'mysite' })

The input shows up and lets me select a file, but never initiates an upload. No errors, no message in the console, nothing.

What more is needed?

cloudinary_fileupload() called upon script inclusion

Please see this commit:
05cd1ec

In this way cloudinary_fileupload() is called as soon as jquery.cloudinary.js is loaded which is far too early for initializing blueimpFileupload (at least in case the you wish to customize the options passed like in my case). At this point I haven't initialized api_key and cloud_name or other binding callbacks.
I want to pass more options so I call later on:

$(".cloudinary_fileupload").cloudinary_fileupload(myCustomOptions);

Could the maintainer explain what is the correct usage in case I want to pass my own options such as maxFileSize, dataType, headers?

Javascript error - public_id is undefined

I've got the attachinary gem functioning almost perfectly. When I go to render a form with an already uploaded / saved cloudinary file, I'm getting the following Javascript error in the latest builds of Chrome / Firefox on OSX:

  Uncaught TypeError: Cannot call method 'match' of undefined -- jquery.cloudinary.js:135

I believe the public_id is undefined even though I see a valid public_id in the hidden value JSON data in the form. Any ideas here?

Also see assembler/attachinary#40

problem with cloudinary_cors.html in IE8 - windows 7

When uploading an image in Internet Explorer 8 i get an error on this line of the cloudinary_cors.html file.

It seems that document.body doesn't have method hasOwnProperty in IE8. It's strange because the comment above this line seems to be saying that this is an explicit check to see if we are running on less than IE9. I removed the if statement and set it to always run

document.body.innerText = parse(window.location.search.slice(1));

and now it seems to run fine.

The commit that made this change stated it was to protect against a XSS vulnerability

Is it safe for me to make this change or is there another cause to my problem you can think of?

Incorrect width used when images marked as cld-responsive are part of inactive Bootstrap TabPanes

Based on this nice article, we tried to use the described responsive behaviour of images served by Cloudinary in a page that uses Bootstrap TabPanels. This resulted in the following behaviour:

  • the generated URLs for the images that are part of the initially active TabPane have proper widths: around 150 pixels for thumbnails.
  • the generated URLs for the images that are part of the inactive TabPanes, the width of the TabPane (or the element containing the TabPane) is used: around 680 pixels in our design.

The resulting images are displayed properly when a TabPane is activated. However, when being loaded an image with a bigger width than required is loaded. This kind of make using this feature useless, since we use TabPanels a lot.

Using the incorrect width is possibly caused by this snippet of code which traverses up to the DOM untill a proper width is found. As soon as the element is found that contains all the TabPanes, THAT width is used since that element is the first one visible... Maybe this approach is a bit 'naive'? Maybe the 'loading' process should only start when the element itself, or direct parent has a width, or make the amount of considered upper elements configurable? Then we could fire a window resize event as soon as a Tab is clicked...

Update, I tested the last suggestion, this works properly. We take the size of the parentNode and fire a window.resize event as soon as a Tab is activated. In what scenario's would you want to traverse further 'up' the hierarchy than just the parent node of the image?

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.