Alibaba_ Open Source 2022-01-27 02:33:09 阅读数:225
The most obvious way is to instantiate a when selecting an object dropzone, Manually create... As before dropzones The way .
Common methods :
Because we need to use dropzone Some styles provided , For example, when previewing, picture style, etc , In this way, you can create it manually , But you also need to use dropzone
Style class , This will lead to initialization twice , An error will be reported on the console , At this time, you need to set the following code before manual initialization :
// Prevent Dropzone from auto discovering this element:
Dropzone.options.myAwesomeDropzone = false;
// This is useful when you want to create the
// Dropzone programmatically later
// Disable auto discover for all elements:
Dropzone.autoDiscover = false;
Example :
Drag the file here
Or click here to open the file manager and select a file
Like above , Both can use dropzone The style of , You can also manually initialize the upload .
configuration option
| Parameters | describe |
| — | — |
| url | except form Elements other than element must specify this parameter ( Or when form Element has no operation attribute ). You can also provide a function , Parameter is files
And must return url(since v3.12.0) |
| method | The default is "post", If necessary, you can also set it to "put". You can also provide a function , Parameter is files
And must return this method(since v3.12.0) |
| parallelUploads | How many files are uploaded at the same time .( See the queue file upload section for more information ) |
| maxFilesize | Company MB |
| filesizeBase | Default 1000. Whether the basis of this definition should use 1000 or 1024 To calculate the file size .1000 It works , because 1000 Bytes are equal to 1 kilobytes ,1024 byte = 1 Kibibyte. You can change it to 1024, If you don't care about effectiveness . |
| paramName | The parameter name received by the file upload backend . Default file
. Be careful : If you set uploadMult
《 A big factory Java Analysis of interview questions + Back end development learning notes + The latest architecture explanation video + Practical project source code handout 》
【docs.qq.com/doc/DSmxTbFJ1cmN1R2dB】 Full content open source sharing
iple by true, that Dropzone Will [] Attach to this name , That is, the backend receives a file[] Array . |
| uploadMultiple | Dropzone Whether to send multiple files in one request . If it's set to true, then fallback
Part of the input
The element must have multiple
attribute . This option will also trigger other events ( Such as processingmultiple
). For more information , See the events section . |
| headers | An object that sends an additional header to the server . Such as :headers: { "My-Awesome-Header": "header value" }
|
| addRemoveLinks | This will add a link to each file , Delete or cancel preview file ( If it has been uploaded ).dictCancelUpload
, dictCancelUploadConfirmation
and dictRemoveFile
Three parameters are optional . |
| previewsContainer | Definition file preview display . If null
Just use Dropzone default . You can use an ordinary html Element or css Selectors . The chosen html Element must contain dropzone-previews
The style class ensures that the preview is displayed normally . |
| clickable | If true
,dropzone The element itself will be clickable , If false
Will not be clickable . Besides , It can also be an ordinary html perhaps css Selectors , Indicates that clicking this element triggers the resource manager . |
| createImageThumbnails | |
| maxThumbnailFilesize | Company MB. When the file name exceeds this limit , Thumbnails will not be generated . |
| thumbnailWidth | If null
, The scale of the image will be used to calculate it . |
| thumbnailHeight | And thumbnailWidth
equally . If both are null, The image will not be adjusted . |
| maxFiles | If not for null
, Define how many files will be processed . If exceeded , event maxfilesexceeded
Will be called . Accordingly dropzone Element gets the class dz-max—files-reached
, So you can provide visual feedback . |
| resize | The function called when creating adjustment information .file
As the first parameter of the function , At the same time, an object containing srcX
, srcY
, srcWidth
、srcHeight
And the same trg*
. These values will be used for ctx.drawImage()
function . |
| init | Dropzone Function called during initialization . You can set the event listener in this function . |
| acceptedFiles | accept
The default implementation function of the function , For checking files mime Type or extension . This is a comma separated mime An array of types and file extensions . Such as .image/*,application/pdf,.psd
. If Dropzone yes clickable
, This option will be used as accept
Parameter input of function . |
| accept | A receiver file
and done
Function as parameter input function . If done
Function call has no arguments , The file will be processed . If you are in the done
The parameter... Was passed in the function ( Such as error messages ) Files will not be uploaded . If the file is too large or does not match mime Type this function will not call . |
| autoProcessQueue | When set to false, You have to call... Yourself myDropzone.processQueue()
Upload files . For more information , See below about processing queues . |
| previewTemplate | A string , It contains templates for each image . Change it to meet your needs , But make sure you provide all the elements correctly . You can create such a container in the page :id="preview-template"
( Set up style=“display: none;”), And then set it up like this :previewTemplate: document.querySelector('preview-template').innerHTML
. |
| forceFallback | The default value is false. If true,fallback
Will be forcibly used . This is a very useful first way to test server implementation , Make sure everything is as expected , And test your fallback
Show how . |
| fallback | Function called when the browser does not support . The default implementation shows fallback
Internal input
Field and add a text . |
| For custom dropzone, You can also use these options |
| dictDefaultMessage | Information displayed before any file is dragged into the area . This is usually an image , But the default is “Drop files here to upload”. |
| dictFallbackMessage | If the browser does not support , The default message will be replaced with this text . The default is “Your browser does not support drag’n’drop file uploads.”. |
| dictFallbackText | This will be added to input file
Before . If you offer one fallback
Elements , Or the option is empty, which will be ignored . The default is “Please use the fallback form below to upload your files like in the olden days.”. |
| dictInvalidFileType | If the file types do not match, the error message displayed . |
| dictFileTooBig | Displays when the file is too large .{
{filesize}}
` and {
{maxFilesize}}
` Will be replaced . |
| dictResponseError | If the server response is invalid, the error message displayed .{
{statusCode}}
` Will be replaced by the status code returned by the server . |
| dictCancelUpload | If addRemoveLinks
by true, Text the text used to cancel the upload link . |
| dictCancelUploadConfirmation | If addRemoveLinks
by true, Text is used to cancel the uploaded text . |
| dictRemoveFile | If addRemoveLinks
by true, Text used to delete a file . |
| dictMaxFilesExceeded | If set maxFiles
, This will be an error message when the setting is exceeded . |
You can also override all default action options . If you provide drop
Option can override the default event handler . You should be familiar with the code , Because you can easily master such Uploads . If you just want to make additional changes , For example, add some filters , Can listen for events .
File upload queue
When a file is added to dropzone, Its status
Set to Dropzone.QUEUED
(accept
After the function check passes ), This means that the file is now in the queue .
If you can choose autoProcessQueue
Set to true
, Then the queue is processed immediately , After the file is deleted or an upload is completed , By calling .processQueue()
, Check how many files are being uploaded , If it's less than option.parallelUploads
,.processFile
Will be called .
If you autoProcessQueue
Set to false
, that .processQueue()
Will not be implicitly called . This means that when you want to upload all the files in the current queue, you must call it yourself .
Layout
Generate a preview for each file HTML, Set up dropzone Defined options previewTemplate
, The default is :
When the file is in the process of uploading ,dz-preview
Medium dz-processing
Will be displayed ; When the file is uploaded dz-success
Will be displayed ; If the file upload error or no network dz-error
Will be displayed , here data-dz-errormessage
The content of will be the information returned by the server .
Override the default template , You can use... In the configuration previewTemplate
Options .
You can file.previewElement
To access the file HTML preview , And set any events . Such as :
success: function (file, response, e) {
var res = JSON.parse(response);
if (res.error) {
$(file.previewTemplate).children(’.dz-error-mark’).css(‘opacity’, ‘1’)
}
}
If you want to break the rules and rewrite previewElement
, You can add... To the elements you want data-dz-*
attribute :
data-dz-name
data-dz-size
data-dz-thumbnail ( This must be <img />
Elements , Then the element's alt
and src
Properties will be Dropzone Automatically change to the corresponding value )
data-dz-uploadprogress ( When the file is in the process of uploading Dropzone Will change the of this element style.width
Value , from 0% To 100%)
data-dz-errormessage
Dropzone Will look for these elements , And change the default options and update its contents .
If you want some specific links, delete a file ( Not built in addRemoveLinks To configure ), You can simply insert the template of the element data-dz-remove attribute .
You don't have to be forced by these usage conventions . If you completely override all default event listeners, you can rebuild your layout from scratch .
If you want your dropzone Look like official Page like that , Use the add style sheets and provided in the installation section spritemaps that will do .
See the theme section , See how to change Dropzone Of UI.
Officials created an example , Configure a few lines of code , Give Way Dropzone It looks and feels exactly the same as jQuery File upload is almost .Check it out!
Dropzone Method
If you want to delete the added files , You can call .removeFile(file)
. This method also triggers removedfile
event .
Here's an example , The file will be deleted automatically after uploading :
myDropzone.on(“complete”, function(file) {
myDropzone.removeFile(file);
});
If you want to delete all the files , Simply use .removeAllFiles()
. Files being uploaded will not be deleted . If you want to cancel the file being uploaded , call .removeAllFiles(true)
The upload will be canceled .
If you set it autoProcessQueue
by false
, You have to call .processQueue() Upload .
visit dropzone All files in , Use myDropzone.files
.
All acceptable documents :.getAcceptedFiles()
So the rejected file :.getRejectedFiles()
All files in the queue :.getQueuedFiles()
Upload all files in :.getUploadingFiles()
If you don't need one anymore dropzone, Call with current sample .disable()
, This will remove the event on that element 、 file . Reactivate use .enable()
.`
If you don't like the browser's default confirm
, You can override Dropzone.confirm
Deal with them :
Dropzone.confirm = function(question, accepted, rejected) {
// Ask the question, and call accepted() or rejected() accordingly.
// CAREFUL: rejected might not be defined. Do nothing in that case.
};
event
–
Dropzone Trigger event when processing file , You can call... Through the current instance .on(eventName, callbackFunction)
Monitoring events .
Because listening to events can only be Dropzone example , Set up your event listener , The best place is in init function .
Dropzone.options.myAwesomeDropzone = {
init: function() {
this.on(“addedfile”, function(file) { alert(“Added file.”); });
}
};
If you create it manually dropzones, You can set the event listener of the instance , Just like this. :
// This example uses jQuery so it creates the Dropzone, only when the DOM has
// loaded.
// Disabling autoDiscover, otherwise Dropzone will try to attach twice.
Dropzone.autoDiscover = false;
// or disable for specific dropzone:
// Dropzone.options.myDropzone = false;
$(function() {
// Now that the DOM is fully loaded, create the dropzone, and setup the
// event listeners
var myDropzone = new Dropzone("#my-dropzone");
myDropzone.on(“addedfile”, function(file) {
/* Maybe display some more file information on your page */
});
})
This is more complicated , There is no need for , Unless you have a good reason to manage instantiation Dropzones.
Dropzone Itself heavily dependent on events , Visual display is done through monitoring . These event listeners are set up in each Dropzone Default configuration , You can override , This replaces the default behavior and implements its own event callback .
List of events
Do not override these configuration options , Unless you know what you're doing . | |
event | describe |
---|---|
All these receive event As the first parameter |
|
drop | The user releases the file to dropzone |
dragstart | The user starts dragging files anywhere |
dragend | Drag end |
dragenter | Users drag files to Dropzone |
dragover | The user drags a file through Dropzone |
dragleave | The user drags a file away Dropzone |
All these receive file As the first parameter |
|
addedfile | When a file is added to the list |
removedfile | Delete a file from the list . You can listen to this event and delete the file from your server |
thumbnail | Generate thumbnails . receive dataUrl As the second parameter |
error | There was a mistake . receive errorMessage As the second parameter , If the error is due to XMLHttpRequest xhr Object is the third parameter . |
processing | When a file is processed ( Because the queue will not process all files immediately ). This incident happened in processingfile It was triggered before . |
uploadprogress | Whenever the file upload process changes, it triggers . get progress As the second parameter , It's a percentage (0 - 100) and bytesSent As the third parameter , Is the number of bytes that have been sent to the server . When the upload is complete dropzone Make sure uploadprogress by 100% And be called once .Warning: This function can be called multiple times using the same progress . |
sending | Sending in each file is triggered .file For the first parameter ,xhr Objects and formData Object as the second and third parameters , You can modify them ( Such as adding CSRF token ) Or add additional data . |
success | The file has been uploaded successfully .file For the first parameter , Get the server response as the second parameter .( This incident is in finished Trigger before . |
complete | Upload success or error . |
canceled | When a file upload is cancelled . |
maxfilesreached | The number of documents received arrives at maxFiles At the limit |
maxfilesexceeded | Every file was rejected , Because the number of files exceeds maxFiles Trigger at the limit |
All these received files As the first parameter , And just be uploadMultiple by true Trigger when |
|
processingmultiple | see processing Description of . |
sendingmultiple | see sending Description of . |
successmultiple | see success Description of . |
completemultiple | see complete Description of . |
canceledmultiple | see canceled Description of . |
Special events | |
totaluploadprogress | Include parameters when triggering total uploadProgress(0 - 100) ,totalBytes and totalBytesSent . This event can be used to display the overall upload progress of all files |
reset | When called, all files in the list are deleted ,dropzone Reset to initial state . |
queuecomplete | When all files in the queue are uploaded . |
The theme
If you want to be right Dropzone The theme is completely customized , in the majority of cases , You can simply replace HTML Template preview , adjustment CSS, You can also create some additional event listeners .
Officials created an example , Configure a few lines of code , Give Way Dropzone It looks and feels exactly the same as jQuery File upload is almost .Check it out!. As you can see , The biggest change is previewTemplate. Then I added some additional event listeners to make it look like it meets my requirements .
However , You can implement your... Completely from scratch UI.
Override the default event listener , Create your own custom Dropzone, It can be like this :
// This is an example of completely disabling Dropzone’s default behavior.
// Do not use this unless you really know what you are doing.
Dropzone.myDropzone.options = {
previewTemplate: document.querySelector(’#template-container’).innerHTML,
// Specifing an event as an configuration option overwrites the default
// addedfile
event handler.
addedfile: function(file) {
file.previewElement = Dropzone.createElement(this.options.previewTemplate);
// Now attach this new element some where in your page
},
thumbnail: function(file, dataUrl) {
// Display the image in your file.previewElement
},
uploadprogress: function(file, progress, bytesSent) {
// Display the progress
}
// etc…
};
The above code obviously lacks practical implementation . Look at the source code , have a look Dropzone Internal implementation .
If you don't need any default Dropzone UI, Only right Dropzone The event handler for 、 Interested in file upload and drag functions , Then you should use the above options for event handling .
Tips
If you don't want the default message prompt ( Drag file upload ( Or click )), You can be in your dropzone
Add an element containing class to the element dz-message
, such dropzone
Will not create a message for you .
Dropzone Or submit your settings form
All hidden form field information in . So when you are using form
In the form of elements , This is a simple way to submit additional data , As for get
still post
It's up to you form
Of method
. Of course you can js Add other parameters to the configuration .
When the event binding is complete ,Dropzone Data will be added to file
object . If it is image
Words , You can go through file.width
and file.height
Access the width and height of the picture . and file.upload
The object will contain the following information :progress
(0-100), total
( The total byte ) and bytesSent
( Bytes uploaded ). In this way, you can customize the upload progress bar by writing information here .
If you want to add extra to the uploaded file ( When there are multiple files, it will be specific to each file ), You can register to send events :
myDropzone.on(“sending”, function(file, xhr, formData) {
// Will send the filesize along with the file as POST data.
formData.append(“filesize”, file.size);
});
After the file was uploaded , Can pass file.previewElement
Access the preview of the uploaded file html. for example :
myDropzone.on(“addedfile”, function(file) {
file.previewElement.addEventListener(“click”, function() {
myDropzone.removeFile(file);
});
});
If you want the whole body
It's all one Dropzone
Instance and show a file preview somewhere , Then you can simply body
Instantiate a Dropzone object , Prompt definition previewsContainer
Options . This previewsContainer
It can be dropzone-previews
or dropzone
class , In order to display the file preview correctly :
new Dropzone(document.body, {
previewsContainer: “.dropzone-previews”,
// You probably don’t want the whole body
// to be clickable to select files
clickable: false
});
Can be in github wiki Look for more examples .
Compatibility
This section describes Dropzone Compatible with browsers and older versions .
Browser support :
Chrome 7+
Firefox 4+
IE 10+
Opera 12+ (MacOS V12 Version not available , Because of its API There is a problem )
copyright:author[Alibaba_ Open Source],Please bring the original link to reprint, thank you. https://en.javamana.com/2022/01/202201270233021715.html