Plupload powerful multi-file bulk upload Plugin

Source: Internet
Author: User
Tags bind error code event listener file size file upload zip silverlight


Plupload is an interface-friendly file upload module on a Web browser that shows upload progress, automatic image thumbnails, and upload chunking. Can upload multiple files at the same time, for your content management system or similar upload program to provide a highly available upload plug-ins.



Plupload powerful multi-file bulk upload Plugin



Plupload This JavaScript control allows you to choose Adobe Flash, Google Gears, HTML5, Microsoft Silverlight, Yahoo Browserplus or normal form form, and so on a variety of ways to upload files.



Plupload also offers other features including: Upload progress reminders, picture reduction, multiple file uploads, drag files to upload controls, file type filtering and chunked uploads. These features are limited in support of different uploading methods.



Attention matters



Block upload Chrome and Firefox 4+ support.
Drag and drop for Firefox and WebKit Kernel browser, Windows version of Safari there are some problems to resolve.
Picture scaling is supported only on firefox3.5+ and Chrome, Safari/opera does not support direct data access to selected files.
Currently, all browsers do not support file type filtering. However, we fill in the HTML5 acceptance file type filter attribute, and once there is support it will work.
Multi-file uploads support only the gecko and WebKit kernel browsers.
How to use



1, through the official website or github address to download plupload source files, extract to your project folder.



2, in the head of the Web page to introduce plug-ins must be JavaScript files



<script src= "/plupload.js" ></script>
<script src= "/plupload.gears.js" ></script> (no need to be removed)
<script src= "/plupload.silverlight.js" ></script> (no need to be removed)
<script src= "/plupload.flash.js" ></script> (no need to be removed, I need to use in my project)
<script src= "/plupload.browserplus.js" ></script> (no need to be removed)
<script src= "/plupload.html4.js" ></script> (no need to be removed)
<script src= "/plupload.html5.js" ></script> (no need to be removed)



3, write upload HTML code, here we only use the most basic HTML structure: A Select File button, a start to upload the file button, and sometimes even the button can not.



<p>
<button id= "Browse" > select File </button>
<button id= "Start_upload" > Start uploading </button>
</p>



4, the instantiation of a Plupload upload object



var uploader = new Plupload. Uploader ({
Browse_button: ' Browse ',//Trigger File Selection dialog box button, for that element ID
URL: ' upload.php ',//server-side upload page address
Flash_swf_url: ' js/moxie.swf ',//swf file, need to configure this parameter when uploading with SWF
Silverlight_xap_url: ' js/moxie.xap '//silverlight file, need to configure this parameter when you need to use the Silverlight method for uploading
});



Invoke the Init () method on the instance object to initialize
Uploader.init ();



Bind various events and do what you want in the event listener function
Uploader.bind (' filesadded ', function (uploader,files) {
Each event listener will pass in some very useful arguments,
We can use the information provided by these parameters to do things like updating the UI, prompting for upload progress, etc.
});
Uploader.bind (' uploadprogress ', function (uploader,file) {
Each event listener will pass in some very useful arguments,
We can use the information provided by these parameters to do things like updating the UI, prompting for upload progress, etc.
});
//......
//......



Finally, register the event with the Start Upload button



document.getElementById (' Start_upload '). onclick = function () {
Uploader.start (); Call the Instance object's start () method to begin uploading the file, but you can also call the method elsewhere
}
Multipart:false//Official explanation is to set the data flow structure passed to the background service, false when using the normal byte stream, if true, then use the Mutlipart format, may be to achieve the function of large attachment sub-upload



If you set the Multipart:true, you can attach a parameter using the Multipart_params argument instead of passing the argument behind the service address as I do. There are other attributes, such as chunk_size,resize, which compress the picture, so the control is good for uploading pictures, so it is recommended to view the official website documentation. If you want to simply pass the attachment and then browse, it is best to set the Multipart:false, because when you set to True, you get in the background of the stream format will be a bit of a problem, my own experience is to use the true upload an HTML document to the database, with



Response.ContentType = "text/html";
Response.BinaryWrite (body);
Response.Flush ();
Response.close ();
Response.End ();



This way, when you view an attachment, the HTML page that you open directly will be doped with some unresolved stream information.



When a file is added, a list of files to upload is displayed in the container



Uploader.bind (' filesadded ',
function (up, files) {
for (var i in files) {
$ (' filelist '). InnerHTML + = '
' + Files[i].name + ' (' + plupload.formatsize (files[i].size) + ')
';
}
});



Progress on File Upload



Uploader.bind (' uploadprogress ',
function (up, file) {
$ (file.id). getElementsByTagName (' B ') [0].innerhtml = ' + file.percent + '% ';
});
Total after successful upload of files



Uploader.bind (' uploadcomplete ',
function (up, files) {
$ (' filelist '). InnerHTML = "The file you selected has been uploaded all, total total" + Files.length + "files";
});



This is an option to complete the upload button. After clicking the button, the attachment is not uploaded.



$ (' ibtmultisubmit '). onclick = function () {
Uploader.start ();
return false;
};
Uploader.init ();



Code for the Background service page:



People on the Internet use this method:



byte[] buffer = NULL;
if (Request.contenttype = = "Application/octet-stream" && request.contentlength > 0) {
Buffer = new Byte[request.inputstream.length];
Request.InputStream.Read (buffer, 0, buffer. Length);
else if (Request.ContentType.Contains ("Multipart/form-data") && Request.Files.Count > 0 && Request.files[0]. ContentLength > 0) {
Buffer = new Byte[request.files[0]. Inputstream.length];
Request.files[0]. Inputstream.read (buffer, 0, buffer. Length);
}



To get the contents of the attachment, I basically is also borrowed from him, get the parameters on the use of request.params["Param1″] can, get to do their own business processing can be."



The only problem that you encounter when you use the control is multipart: true and false, the stream that is fetched is different. And it does not seem like uploadify to provide dynamic access to the parameters of the function, so if some want to pass to the background of the parameters are not set when the page initialization, you can consider the transformation method, such as set the parameters, triggering the event to initialize the control again. The control does not support IE6, and other browsers support it very well.





Configuration parameters




When instantiating a Plupload object, that isnew plupload.Uploader(), you need to pass in an object as a configuration parameter. The Plupload instance that appears in the subsequent content is thenew plupload.Uploader()resulting instance object



Property type Default Value Description
Browse_button String/dom The DOM element that triggers the File selection dialog box, which pops up the File selection dialog box when the element is clicked. The value can be the DOM element object itself, or it can be the ID of the DOM element
Url String Server-side to receive and process the upload file script address, can be relative path (compared to the current call Plupload document), can also be absolute path
Filters Object { } You can use this parameter to restrict the type, size, and so on of the uploaded file, which is passed in as an object, which includes three properties:mime_types: The type used to qualify the uploaded file, an array, and each element of the array is an object, The object has title and extensions two properties, title is the name of the filter, extensions is a file extension, and multiple times are separated by commas. This property defaults to an empty array, which is not restricted.

max_file_size: to limit the size of the uploaded file, if the file volume exceeds this value, you cannot be selected. The value can be a number, B, or a string, consisting of numbers and units, such as ' 200kb '

prevent_duplicates: allow duplicate files to be selected, true to disallow, false to allow, default to False. If two files have the same file name and size, they are considered duplicate files

Filters complete configuration examples are as follows (you can, of course, configure only one of these):
Filters: {   mime_types: [//Only allow uploading of pictures and zip files     {title: "Image Files", Extensions: "Jpg,gif,png"},      {title: "Zi P Files ", Extensions:" Zip "}   ],   max_file_size: ' 400kb ',//MAX upload only 400kb file   prevent_duplicates:true//Not allowed Duplicate file}
Headers Object Set the custom header information when uploading, in the form of a key/value pair, the key represents the header information property name, and the key represents the property value. The Html4 upload method does not support setting this property.
Multipart Boolean True Thetruefile will bemultipart/form-datauploaded in the form of false when the file is uploaded in binary format. Html4 Upload method does not support the binary format to upload files, in the Flash upload mode, binary upload also has a problem. and binary format upload also need to do special processing on the server side. Generally we use the form of Multipart/form-data to upload the file is enough.
Multipart_params Object Additional parameters are uploaded as key/value pairs, and the server side uses $_post to get these parameters (in PHP, for example). Like what:
Multipart_params: {   One: ' 1 ',   two: ' 2 ',   three: {//value can also be a literal object     A: ' 4 ',     B: ' 5 '   },   four: [ ' 6 ', ' 7 ', ' 8 '  //can also be an array}
Max_retries Number 0 plupload.HTTP_ERRORthe number of retries when an error occurs, when 0 indicates no retry
Chunk_size Number/string 0 When the fragment uploads the file, each piece of file is cut into the size, the number is the unit bytes. You can also use a string with units, such as"200kb". When this value is 0, the fragment upload feature is not used
Resize Object can use this parameter to compress the picture that will be uploaded, which is an object that contains 5 properties: Width: Specifies the width of a compressed picture , if this property is not set, the width of the original picture is assumed

Height: Specifies the height of the compressed picture, or the height of the original picture if it is not set

crop: whether to crop the picture

quality: The quality of the compressed picture, only valid for images in JPG format, default is 90.qualitycan be used withwidthandheight, but it can also be used alone, and when used alone, the width of the picture will not change after compression, but because of the reduced quality, So the volume gets smaller.

preserve_headers: Preserve the metadata for the picture after compression,truefor retention,Fals Eis not persisted, the default istrue. Deleting a picture's metadata can reduce the size of the picture a little bit. The configuration example for the

resize parameter is as follows:
 resize: {width:100, height:100, CRO P:true, quality:60, preserve_headers:false} 
Drop_element Dom/string/array Specifies the drag-and-drop area when you choose to upload files using drag-and-drop, which means you can drag files to the area to select the files. The value of this parameter can be the ID of a DOM element, the DOM element itself, or an array that includes multiple DOM elements. If you do not set this parameter, drag and drop the upload feature is not available. Currently only HTML5 upload method to support drag and drop upload.
Multi_selection Boolean True Whether you can select multiple files in the File Browsing dialog box, true can, false is not possible. The default is true, where multiple files can be selected. It should be noted that in some environments that do not support multiple-selection files, the default value is False. For example, in iOS7 's Safari browser, there are bugs that make it impossible to select multiple files. Of course, in the Html4 upload way, also can not select multiple files.
Required_features Mix You can use this parameter to set some of the features you must need, Plupload will choose the right way to upload according to your settings. Because, different upload way, support function is different, such as drag and drop upload only HTML5 upload way support, picture compression only html5,flash,silverlight upload way support. The value of the parameter is a mixed type, which can be a comma-delimited string,
Unique_names Boolean False True will generate a unique file name for each uploaded file and post it to the server as an additional parameter, with thenamevalue being the generated file name.
Runtimes String Html5,flash,
Silverlight
Html4
Used to specify the way to upload, specify multiple upload methods, separate them with commas. In general, you do not need to configure this parameter, because plupload by default will be based on your other parameters configured to choose the most appropriate way to upload. If there is no special request, Plupload will first choose HTML5 upload mode, if the browser does not support HTML5, will use Flash or Silverlight, if neither of the previous support, will use the most traditional html4 upload method. You can configure this parameter if you want to specify an upload method, or change the order of precedence of the upload method.
File_data_name String File Specifies the name of the file field when the file is uploaded, by defaultfile, for example, in PHP you can use$_FILES['file']to get uploaded file information
Container Dom/string Used to specify the parent container of the HTML structure created by Plupload, which defaults to thebrowse_buttonparent element specified earlier. The value of this parameter can be either the ID of an element or the DOM element itself.
Flash_swf_url String js/moxie.swf Flash upload Component URL address, if it is relative path, then the relative is called Plupload HTML document. This parameter is used when uploading using flash.
Silverlight_xap_url String Js/moxie.xap The URL address of the Silverlight upload component, or, if it is a relative path, the corresponding HTML document that invokes the Plupload. This parameter is used when using the Silverlight upload method.




Description of Events




To understand the health of plupload, it is in these events



Init
The Listener function parameter is triggered when the Plupload initialization completes:(uploader)

uploaderFor the current Plupload instance object
Postinit
Triggers the listener function argument after the Init event occurs:(uploader)

uploaderFor the current Plupload instance object
Optionchanged
The listener function argument is triggered when the current configuration parameter is changed using the SetOption () method of the Plupload instance:(uploader,option_name,new_value,old_value)

uploaderFor the current Plupload instance object, for the changedoption_nameparameter name, for thenew_valuechanged value, for theold_valuevalue before the change
Refresh
This event is triggered when the refresh () method of the Plupload instance is invoked, and it is not clear what other actions will trigger the event, but as I have tested, adding the file to the upload queue also triggers the event. Listener function Parameters:(uploader)

uploaderFor the current Plupload instance object
StateChanged
Triggers the Listener function parameter when the status of the upload queue changes:(uploader)

uploaderFor the current Plupload instance object
UploadFile
The Listener function parameter is triggered when a file in the upload queue starts to upload:(uploader,file)

uploaderIs the current Plupload instance object, whichfileis the file object that triggered this event
Beforeupload
Triggers a listener function argument before a file in the queue is about to begin uploading:(uploader,file)

uploaderIs the current Plupload instance object, whichfileis the file object that triggered this event
Queuechanged
When the upload queue changes after the trigger, that is, the upload queue new files or remove files. The queuechanged event triggers the listener function argument before the filesadded or filesremoved event:(uploader)

uploaderFor the current Plupload instance object
Uploadprogress
Will be triggered in the file upload process, you can use this event to display the upload progress listening function parameters:(uploader,file)

uploaderIs the current Plupload instance object, whichfileis the file object that triggered this event
Filesremoved
Triggering listener function parameters when files are removed from the upload queue:(uploader,files)

uploaderIs the current Plupload instance object,filesan array in which the element is the file object removed by this event
Filefiltered
The significance of the event is not known, but according to the test, the event triggers the listener function argument before each file is added to the upload queue:(uploader,file)

uploaderIs the current Plupload instance object, whichfileis the file object that triggered this event
filesadded
Triggers the Listener function parameter when the file is added to the upload queue:(uploader,files)

uploaderIs the current Plupload instance object,filesan array of elements that are added to the file object in the upload queue for this time
fileuploaded
Triggers a listener function parameter when a file in the queue completes uploading:(uploader,file,responseobject)

uploaderIs the current Plupload instance object, thefileinformation object returned for the server for the file object that triggered this event, andresponseObjectit has the following 3 properties:

response: The text returned by the server

responseheaders: header information returned by the server

Status: The HTTP status code returned by the server, such as 200
chunkuploaded
When using file small piece upload function, each small piece uploads completes to trigger the listener function parameter:(uploader,file,responseobject)

uploaderIs the current Plupload instance object, thefileinformation object returned for the server for the file object that triggered this event, andresponseObjectit has the following 5 properties:

Offset : The number of offsets in the overall file of the file's small slice

response: The text returned by the server

responseheaders: header information returned by the server

Status: The HTTP status code returned by the server, such as 200

Total : The overall size, in bytes, of the file (which refers to the file that was cut into a number of small pieces of files)
Uploadcomplete
When all files in the upload queue are uploaded, the listener function parameters are triggered:(uploader,files)

uploaderFor the current Plupload instance object,filesan array of elements that are all file objects that have been uploaded for this time
Error
Triggering listener function Arguments when an error occurs:(uploader,errobject)

uploaderIs the current Plupload instance object,errObjectan Error object that contains at least 3 properties (because different types of errors may differ):

Code : error codes, refer to the constant properties defined on the plupload that represent error codes

File : files object associated with this error

Message : error messages
Destroy
The listener function argument is triggered when the Destroy method is invoked:(uploader)

uploaderFor the current Plupload instance object




Plupload the properties of an instance






Property Description
Id Unique identification ID of the Plupload instance
State Current upload state, the possible value isplupload.STARTEDorplupload.STOPPED, the value is controlled by the Plupload instancestop()orstatr()method. Default toplupload.STOPPED
Runtime Current use of the Upload method
Files The current upload queue is an array of file objects in the upload queue
Settings The current configuration Parameter object
Total Queueprogress object that represents the overall progress information




. Methods of Plupload examples



Method Description
Init () Initialize Plupload instance
SetOption (option, [value]) Set a specific configuration parameter, option is the parameter name, and value is the parameter value to set. Option can also be an object that consists of parameter names and parameter value key/value pairs so that you can set multiple arguments at once, and the second parameter value of the method is ignored.
GetOption ([option]) Gets the current configuration parameter, the parameter option is the name of the configuration parameter that needs to be obtained, and if option is not specified, all configuration parameters are obtained
Refresh () Refreshes the current instance of Plupload and does not yet understand when it needs to be used
Start () Start uploading files from the queue
Stop () To stop file uploads in the queue
Disablebrowse (disable) Disables or enables the Plupload file browse button, which is disabled for thedisabletruetime beingfalseenabled. Default totrue
GetFile (ID) To get a file object by ID
AddFile (file, [FileName]) Adds a file to the upload queue and triggers an event if the file is successfully addedFilesAdded. The parameter file is the file to add, which can be a native file, or a Plupload file object, or aninput[type="file"]element, or an array that includes the preceding few things; filename Specifies the name for the file
RemoveFile (file) Remove file from upload queue, parameterfileis plupload file object or previously specified file name
Splice (start, length) Removes a portion of a file from the upload queue, the number of files to remove from the queue, and thestartlengthreturned value of the method to the file being removed. This method triggersFilesRemoved andQueueChangedevents
Trigger (name, multiple) Triggers an event.nameis the name of the event to be triggered, and theMultipleargument that is passed to the listener function of the event is an object
Haseventlistener (name) Used to determine whether an event has a listener function, annameevent name
Bind (name, func, scope) Bind a listener function to an event, thenameevent name, the Listener function, the scope of the listener function,funcwhich isscopethe point of this in the listener function.
Unbind (name, func) Remove the listener function for the event, thenameevent name, and thefunclistener function to remove
Unbindall () Remove all listener functions from all events
Destroy () Destroying Plupload instances




Properties and methods of File objects




In many event listener functions, the file object is provided to you



Properties/Methods Description
Id File ID
Name filename, such as "Myfile.gif"
Type File types, such as "Image/jpeg"
Size File size, in bytes, that value may change when client compression is enabled
Origsize The original size of the file, in bytes
Loaded The size, in bytes, of the uploaded part of the file
Percent The percentage of uploaded parts of the file, such as 50, indicates that 50% has been uploaded.
Status The state of the file, which may be one of several values:plupload.QUEUED,,plupload.UPLOADINGplupload.FAILED,plupload.DONE
LastModifiedDate The time the file was last modified
Getnative () Get the native file object
GetSource () Get Moxie.file object, want to know what Moxie is, can look down Https://github.com/moxiecode/moxie/wiki/API
Destroy () Destroying a File object




Properties of the Queueprogress object




The total property of the Plupload instance is a Queueprogress object




Property Description
Size Total size of all files in the upload queue, in bytes
Loaded Total size, in bytes, of the currently uploaded files in the queue
Uploaded The number of uploaded files that have been completed
Failed Number of files failed to upload
Queued The number of files left in the queue (that is, files that have already been uploaded) that need to be uploaded
Percent The percentage of the entire queue that has been uploaded, such as 50 on behalf of 50%
Bytespersec Upload rate, unit byte/s, i.e. bytes/sec




Plupload attributes on a namespace




There are some properties on the namespace of the plupload to represent some constants. Remember, not the properties of the Plupload instance, but the Plupload properties


Thewhen the file size exceeds the maximum value that plupload can handle
Property name Description
VERSION Version number of the current plupload
STOPPED A value of 1, representing the property value of the Plupload instance when the upload queue has not been uploaded or the file in the upload queue has been uploaded.state
Started A value of 2 that represents the property value of the Plupload instance when the file in the queue is being uploadedstate
QUEUED A value of 1 that represents the property value of the file object when a file has been added to the queue for uploadstatus
Uploading A value of 2 that represents the property value of the file object when a file is being uploadedstatus
FAILED A value of 4 that represents the property value of the file object after a file has failed to uploadstatus
Done A value of 5 that represents the property value of the file object after a file was uploaded successfullystatus
Generic_error Value is-100, error code when a common error occurs
Http_error A value of-200, an error code when an HTTP network error occurs, such as the status code returned by the service gas port is not 200
Io_error A value of-300, error code when a disk read or write error occurs, such as a file that is not readable on the local
Security_error Value is-400, error code when an error occurs because of a security problem
Init_error Value is-500, error code with error during initialization
File_size_error Value is-600, error code when the selected file is too large
File_extension_error Value is-601, error code when the selected file type does not meet the requirements
File_duplicate_error Value is-602, error code when duplicate files are selected and no duplicate files are allowed in the configuration
Image_format_error Value is-700, error code when picture format error occurs
Image_memory_error Error code when a memory error occurs
image_dimensions_error value is-702, and the error code

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.