• Stars
    star
    116
  • Rank 303,894 (Top 6 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created over 12 years ago
  • Updated over 10 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Attachments Plugin for Mongoose.js with Support for ImageMagick Styles and Multiple Storage Backends

What's mongoose-attachments?

Mongoose-Attachments is an attachments plugin for Mongoose.js. It handles ImageMagick transformations for the following providers:

Stable Release

You're reading the documentation for the next release of Mongoose-Attachments, which should be 0.1.0. The current stable release is 0.0.4.

Currently, Mongoose-Attachments is undergoing restructuring as we are moving the different storage providers into submodules. If you plan to use 0.0.4, do make sure that you use the [documentation for 0.0.4] (https://github.com/heapsource/mongoose-attachments/blob/v0.0.4/README.md).

Installation

Note: Mongoose-Attachments is bundled with each provider.

Usage

The following example extends the 'Post' model to use attachments with a property called 'image' and three different styles.

var mongoose = require('mongoose');
var attachments = require('mongoose-attachments-aws2js');

var PostSchema = new mongoose.Schema({
  title: String,
  description: String
});

PostSchema.plugin(attachments, {
  directory: 'achievements',
  storage: {
    providerName: 'aws2js',
    options: {
      key: '<key>',
      secret: '<secret>',
      bucket: '<bucket>'
    }
  },
  properties: {
    image: {
      styles: {
        original: {
          // keep the original file
        },
        small: {
          resize: '150x150'
        },
        medium: {
          resize: '120x120'
        },
        medium_jpg: {
          '$format': 'jpg' // this one changes the format of the image to jpg
        }
      }
    }
  }
});

var Post = mongoose.model('Post', PostSchema);

Using with Express.js uploads

Assuming that the HTML form sent a file in a field called 'image':

app.post('/upload', function(req, res, next) {
  var post = new mongoose.model('Post')();
  post.title = req.body.title;
  post.description = req.body.description;
  post.attach('image', req.files.image, function(err) {
    if(err) return next(err);
    post.save(function(err) {
      if(err) return next(err);
      res.send('Post has been saved with file!');
    });
  })
});

Using with an stand-alone app files

var post = new mongoose.model('Post')();
post.title = 'Title of the Post';
post.description = 'Description of the Post';
post.attach('image', {
    path: '/path/to/the/file.png'
  }, function(err) {
    if(err) return next(err);
    post.save(function(err) {
      if(err) return next(err);
      console.log('Post has been Saved with file');
    });
})

Using Local Storage

With mongoose-attachments-localfs.

var path = require('path');
var attachments = require('mongoose-attachments-localfs');

MySchema.plugin(attachments, {
  directory: '/absolute/path/to/public/images',
  storage : {
    providerName: 'localfs'
  },
  properties: {
    image: {
      styles: {
        original: {
          // keep the original file
        },
        thumb: {
          thumbnail: '100x100^',
          gravity: 'center',
          extent: '100x100',
          '$format': 'jpg'
        },
        detail: {
          resize: '400x400>',
          '$format': 'jpg'
        }
      }
    }
  }
});
MySchema.virtual('detail_img').get(function() {
  return path.join('detail', path.basename(this.image.detail.path));
});
MySchema.virtual('thumb_img').get(function() {
  return path.join('thumb', path.basename(this.image.thumb.path));
});

The URL to the images would then be http://<your host>/<mount path>/images prepended to the value of MyModel.detail_img and MyModel.thumb_img.

Metadata

When mongoose-attachments is used with images, it can provide basic information for each one of the specified styles:

Example:

{
  "dims" : {
    "w" : 120,
    "h" : 103
  },
  "depth" : 8,
  "format" : "PNG",
  "oname" : "dragon.png",
  "mtime" : ISODate("2012-05-22T06:21:53Z"),
  "ctime" : ISODate("2012-05-22T06:21:53Z"),
  "size" : 26887,
  "path" : "/achievements/4fbaaa31db8cec0923000019-medium.png",
  "defaultUrl" : "http://gamygame-dev.s3.amazonaws.com/achievements/4fbaaa31db8cec0923000019-medium.png"
}

Styles and ImageMagick Transformations

Transformations are achieved by invoking the convert command from ImageMagick and passing all the properties of the style as arguments.

For more information about convert, take a look at http://www.imagemagick.org/script/command-line-options.php

Example in convert command:

convert source.png -resize '50%' output.png

Example in plugin options:

styles: {
  small: {
    resize: '50%'
  }
}

Keeping the Original File

styles: {
  original: {
    // no transformations
  }
}

Multiples Transformations

Use another properties under the style to provide more transformations

styles: {
  small: {
    crop: '120x120',
    blur: '5x10' //radius x stigma
  }
}

More information about 'blur' at the [ImageMagick website] http://www.imagemagick.org/script/command-line-options.php#blur

Changing the Destination Format

You can change the destination format by using the special transformation '$format' with a known file extension like png, jpg, gif, etc.

Example:

styles: {
  as_jpeg: {
    '$format': 'jpg'
  }
}

Note: DO NOT include the dot in the extension.

Supported Formats

There are two possibilities to define which file formats should be supported:

  1. white list (default)
  2. formats listed with certain flags by convert -list format
White List

The default white list contains:

  • PNG
  • GIF
  • TIFF
  • JPEG

To add a format call the following method before using the plugin in the mongoose schema:

attachments.registerDecodingFormat('BMP');
Formats Provided by ImageMagick

ImageMagick (or GraphicsMagick) list the supported formats when calling convert -list format (or identify). The formats are flagged to show which operations are supported with each:

  • * native blob support (only ImageMagick, not GraphicsMagick)
  • r read support
  • w write support
  • + support for multiple images

You can register the formats that are supported for read operation like so:

attachments.registerImageMagickDecodingFormats();

To register formats supporting different operations there is a more general function. Specifying certain operations will select only those formats that support all of them. Formats supporting only a subset won't be included. The following call yields the list of formats that support read,write,multi:

attachments.registerImageMagickFormats({ read: true, write: true, multi: true });

If you want to use the output list that was generated for your own benefit you can specify a callback as second argument to that above method. Note, however, that in that case the supported decoding formats won't be changed on the plugin.

You could use that callback to assure that the formats you want your client to support are indeed supported by the backing ImageMagick (or GraphicsMagick) installation. For example, checking TIFF support:

attachments.registerImageMagickFormats({ read: true }, function(error, formats) {
  if (error) throw new Error(error);
  else if (formats && formats.length > 0) {
    if (formats.indexOf('TIFF') < 0) {
      throw new Error('No TIFF support!');
    }
  } else {
    throw new Error("No formats supported for decoding!");
  }
});

Contributors

License (MIT)

Copyright (c) 2011-2013 Firebase.co - http://firebase.co

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

More Repositories

1

active_model_otp

Adds methods to set and authenticate against one time passwords (Two-Factor Authentication). Inspired in AM::SecurePassword
Ruby
770
star
2

fire

An experimental Framework that uses JSON structures to simplify the definition of complex behavior from asynchronous sources in Node.js.
JavaScript
24
star
3

vcap-node-client

VCAP(Cloudfoundry) Client for Node.js
JavaScript
11
star
4

mongoose-attachments-aws2js

S3 Storage Provider for mongoose-attachments backed by the aws2js library.
JavaScript
10
star
5

google-authenticator

Mirror of https://code.google.com/p/google-authenticator/
Java
8
star
6

google-authenticator.android

Mirror of https://code.google.com/p/google-authenticator.android/
Java
8
star
7

mongoose-attachments-localfs

Simple File System Storage Provider for mongoose-attachments
JavaScript
8
star
8

safe_datejs

Safe(Node.js isolated) wrapper around http://www.datejs.com/
JavaScript
7
star
9

dependency-foo

Stupid-proof Directed Acyclic Graph(DAG)
JavaScript
6
star
10

mongoose-attachments-knox

S3 Storage Provider for mongoose-attachments backed by Knox library
JavaScript
6
star
11

monol

A progressive effort to build a Node.JS module that allows calls into CIL universe(Mono Runtime) from Node.JS and Javascript
C++
5
star
12

BlackLinks

.NET Web Application Framework and Runtime on top of Nginx WebServer
C
4
star
13

mongoose-attachments-samples

Example apps for Mongoose-Attachments
JavaScript
4
star
14

pseudo

A simple loader of actions and middlewares for express.js
JavaScript
3
star
15

simple_queue

A simple background system for Ruby
Ruby
3
star
16

firedroid

Android Async Tasks and Http Requests made easy!
Java
3
star
17

weekly

Stupid Node.js TODO's :)
JavaScript
2
star
18

tttd

Simple Android TODO List Application
Java
2
star
19

scarlett

Ruby
2
star
20

nuodb-ruby

Ruby
1
star
21

nuodb-jruby

Ruby
1
star
22

twitter-cache

Ruby
1
star
23

jitsu-control-android

Android client for Nodejitsu.com
Java
1
star