on
Italy
- Get link
- X
- Other Apps
bower install dropzone
There are also third-party packages providing support for ReactJS and implementing the widget as an Angular directive.
Pre-minified versions are also supplied in the package.dropzone-amd-module.js
instead.div
tag. Using a form, however, means less options to set — most notably
the URL, which is the most important configuration property.dropzone
class, for example:
Technically that’s all you need to do, though in most cases you’ll
want to set some additional options. The format for that is as follows:Dropzone.options.WIDGET_ID = {
//
};
To derive the widget ID for setting the options, take the ID you defined in your HTML and camel-case it. For example, upload-widget
becomes uploadWidget
:Dropzone.options.uploadWidget = {
//
};
You can also create an instance programmatically:var uploader = new Dropzone(‘#upload-widget’, options);
Next up, we’ll look at some of the available configuration options.url
option defines the target for the upload form,
and is the only required parameter. That said, if you’re attaching it to
a form element then it’ll simply use the form’s action
attribute, in which case you don’t even need to specify that.method
option sets the HTTP method and again, it
will take this from the form element if you use that approach, or else
it’ll simply default to POST
, which should suit most scenarios.paramName
option is used to set the name of the
parameter for the uploaded file; were you using a file upload form
element, it would match the name
attribute. If you don’t include it then it defaults to file
.maxFiles
sets the maximum number of files a user can upload, if it’s not set to null.clicked
parameter to disable this by setting it to false
, or alternatively you can provide an HTML element or CSS selector to customize the clickable element.maxFilesize
property determines the maximum file size in megabytes. This defaults to a size of 1000 bytes, but using the filesizeBase
property, you could set it to another value — for example, 1024 bytes.
You may need to tweak this to ensure that your client and server code
calculate any limits in precisely the same way.acceptFiles
parameter can be used to restrict the
type of file you want to accept. This should be in the form of a
comma-separated list of MIME-types, although you can also use wildcards.acceptedFiles: ‘image/*’,
thumbnailWidth
and/or the thumbnailHeight
configuration options.thumbnailWidth
and thumbnailHeight
to null
, the thumbnail won’t be resized at all.resize
function.dz-image
class provided by the package sets the thumbnail size in the CSS, so you’ll need to modify that accordingly as well.accept
option allows you to provide additional
checks to determine whether a file is valid, before it gets uploaded.
You shouldn’t use this to check the number of files (maxFiles
), file type (acceptedFiles
), or file size (maxFilesize
), but you can write custom code to perform other sorts of validation.accept
option like this:accept: function(file, done) {
if ( !someCheck() ) {
return done('This is invalid!');
}
return done();
}
As you can see it’s asynchronous; call done()
with no
arguments and validation passes, or provide an error message and the
file will be rejected, displaying the message alongside the file as a
popover.POST/PUT/DELETE
endpoints check the request headers for a valid token. Suppose you outputted your token like this:
Then, you could add this to the configuration:headers: {
'x-csrf-token': document.querySelectorAll('meta[name=csrf-token]')[0].getAttributeNode('content').value,
},
Alternatively, here’s the same example but using jQuery:headers: {
'x-csrf-token': $('meta[name="csrf-token"]').attr('content')
},
Your server should then verify the x-csrf-token
header, perhaps using some middleware.
into your form containing input controls, setting the class name on the element to fallback
. For example:
Alternatively, you can provide a function to be executed when the browser doesn’t support the plugin using the fallback
configuration parameter.forceFallback
to true
, which might help during development.error
configuration parameter. The first argument is the file, the error
message the second and if the error occured server-side, the third
parameter will be an instance of XMLHttpRequest
.dictDefaultMessage
is used to set the text which appears in the middle of the dropzone, prior to someone selecting a file to upload.dict
– in the documentation.Dropzone.options.uploadWidget = {
init: function() {
this.on('success', function( file, resp ){
...
});
},
...
};
Or the alternative approach, which is useful if you decide to create the Dropzone instance programatically:var uploader = new Dropzone('#upload-widget');
uploader.on('success', function( file, resp ){
...
});
Perhaps the most notable is the success
event, which is fired when a file has been successfully uploaded. The success
callback takes two arguments; the first, a file object and the second an instance of XMLHttpRequest
.addedfile
and removedfile
for when a file has been added or removed from the upload list, thumbnail
which fires once the thumbnail has been generated and uploadprogress
which you might use to implement your own progress meter.drop
, dragstart
, dragend
, dragenter
, dragover
and dragleave
.accept()
option, which you can use to run checks (validation) on files before they get uploaded.init: function() {
this.on('thumbnail', function(file) {
if ( file.width < 1024 || file.height < 768 ) {
file.rejectDimensions();
}
else {
file.acceptDimensions();
}
});
},
accept: function(file, done) {
file.acceptDimensions = done;
file.rejectDimensions = function() {
done('The image must be at least 1024 by 768 pixels in size');
};
},
If you’re implementing CSRF protection, you may want to add something like this to your layouts:
Now the JavaScript – notice we’re not using jQuery!Dropzone.options.uploadWidget = {
paramName: 'file',
maxFilesize: 2, // MB
maxFiles: 1,
dictDefaultMessage: 'Drag an image here to upload, or click to select one',
headers: {
'x-csrf-token': document.querySelectorAll('meta[name=csrf-token]')[0].getAttributeNode('content').value,
},
acceptedFiles: 'image/*',
init: function() {
this.on('success', function( file, resp ){
console.log( file );
console.log( resp );
});
this.on('thumbnail', function(file) {
if ( file.width < 640 || file.height < 480 ) {
file.rejectDimensions();
}
else {
file.acceptDimensions();
}
});
},
accept: function(file, done) {
file.acceptDimensions = done;
file.rejectDimensions = function() {
done('The image must be at least 640 x 480px')
};
}
};
A reminder that you’ll find the code for this example on our GitHub repository.dropzone
and its component elements have classes prefixed with dz-
; for example dz-clickable
for the clickable area inside the dropzone, dz-message
for the caption, dz-preview
/ dz-image-preview
for wrapping the previews of each of the uploaded files, and so on. Take a look at the dropzone.css
file for reference.dz-drag-hover
class, which gets added automatically by the plugin.previewTemplate
configuration property. Here’s what the default preview template looks like:
As you can see, you get complete control over how files are rendered
once they’ve been queued for upload, as well as success and failure
states.var upload = multer( { dest: 'uploads/' } );
app.post( '/upload', upload.single( 'file' ), function( req, res, next ) {
// Metadata about the uploaded file can now be found in req.file
});
Before we continue the implementation, the most obvious question to
ask when dealing with a plugin like DropzoneJS which makes requests for
you behind the scenes is: “what sort of responses does it expect?”2xx
response code. The content and format of your response is entirely up
to you, and will probably depend on how you’re using it; for example you
might return a JSON object which contains a path to the uploaded file,
or the path to an automatically generated thumbnail. For the purposes of
this example we’ll simply return the contents of the file object – i.e.
a bunch of metadata – provided by Multer:return res.status( 200 ).send( req.file );
The response will look something like this:{ fieldname: 'file',
originalname: 'myfile.jpg',
encoding: '7bit',
mimetype: 'image/jpeg',
destination: 'uploads/',
filename: 'fbcc2ddbb0dd11858427d7f0bb2273f5',
path: 'uploads/fbcc2ddbb0dd11858427d7f0bb2273f5',
size: 15458 }
application/json
– then DropzoneJS default error plugin expects the response to look like this:{
error: 'The error message'
}
If you aren’t using JSON, it’ll simply use the response body, for example:return res.status( 422 ).send( 'The error message' );
image/
. ES6’s String.prototype.startsWith()
is ideal for this, but let’s install a polyfill for it:npm install string.prototype.startswith --save
if ( !req.file.mimetype.startsWith( 'image/' ) ) {
return res.status( 422 ).json( {
error : 'The uploaded file must be an image'
} );
}
var dimensions = sizeOf( req.file.path );
if ( ( dimensions.width < 640 ) || ( dimensions.height < 480 ) ) {
return res.status( 422 ).json( {
error : 'The image must be at least 640 x 480px'
} );
}
var express = require( 'express' );
var multer = require( 'multer' );
var upload = multer( { dest: 'uploads/' } );
var sizeOf = require( 'image-size' );
var exphbs = require( 'express-handlebars' );
require( 'string.prototype.startswith' );
var app = express();
app.use( express.static( __dirname + '/bower_components' ) );
app.engine( '.hbs', exphbs( { extname: '.hbs' } ) );
app.set('view engine', '.hbs');
app.get( '/', function( req, res, next ){
return res.render( 'index' );
});
app.post( '/upload', upload.single( 'file' ), function( req, res, next ) {
if ( !req.file.mimetype.startsWith( 'image/' ) ) {
return res.status( 422 ).json( {
error : 'The uploaded file must be an image'
} );
}
var dimensions = sizeOf( req.file.path );
if ( ( dimensions.width < 640 ) || ( dimensions.height < 480 ) ) {
return res.status( 422 ).json( {
error : 'The image must be at least 640 x 480px'
} );
}
return res.status( 200 ).send( req.file );
});
app.listen( 8080, function() {
console.log( 'Express server listening on port 8080' );
});
Comments
Post a Comment