java uploads files to jquery.uploadify on the server

Posted by Ned on Fri, 21 Jun 2019 03:07:38 +0200

Based on jquery file upload control, support ajax refreshless upload, multiple files upload at the same time, upload progress display, delete uploaded files.

JQuery 1.4 or above, flash player 9.0.24 or above are required.

There are two versions, one is flash and the other is HTML 5. HTML 5 pays ~so here's just the flash version



1. jsp front-end pages and scripts:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
String dclb = request.getParameter("dclb");
String shi = request.getParameter("shi");
String xian = request.getParameter("xian");
String year = request.getParameter("year");
%>

<!DOCTYPE>
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>Disaster Information Input</title>
    
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->
	<link rel="stylesheet" type="text/css" href="css/table.css">
	<link rel="stylesheet" type="text/css" href="css/jcsj/sjdr/sjdr.css">
	
	<!-- frame -->	
	<link rel="stylesheet" type="text/css" href="scripts/libs/uploadify/uploadify.css">
    <script type="text/javascript" src="scripts/libs/uploadify/jquery-2.2.1.min.js"></script> 
    <script type="text/javascript" src="scripts/libs/uploadify/jquery.uploadify.min.js"></script>  
	
	<!-- business -->
	 <script type="text/javascript">  
    $(function(){  
        $("#uploadify").uploadify({
            'debug'     : false, //Open debugging  
            'auto'           : false, //Whether to upload automatically     
            'swf'            : 'scripts/libs/uploadify/uploadify.swf',  //Introduce uploadify.swf    
            'uploader'       : '../../../jcsj/uploadFile',//Request path    
            'queueID'        : 'fileQueue',//Queue id, used to show upload progress    
            'width'     : '75',  //Button width    
            'height'    : '24',  //Button Height  
            'cancelImg'      : 'scripts/libs/uploadify/cancel.png',
            'queueSizeLimit' : 200,  //Number of files uploaded simultaneously    
            'fileTypeDesc'   : 'Excel file',    //Optional File Type Description  
            'fileTypeExts'   : '*.MDB*;*.xls;*.xlsx', //Control the extension of uploadable files 
            'multi'          : true,  //Allow multi-file upload   
            //'progressData':'percentage', / / / Settings file upload display data, with'percentage'or'speed' two parameters (percentage and speed) 
            'buttonText'     : 'Select Files',//Text on the button    
            'fileSizeLimit' : '50MB', //Setting a single file size limit     
            'fileObjName' : 'uploadify',  //name of <input type="file"/>    
            'method' : 'post',    
            'removeCompleted' : true,//Automatically delete queues after upload is completed    
            'onFallback':function(){      
                alert("You did not install FLASH Control, unable to upload pictures! Please install FLASH Control and try again.");      
            },
             onQueueComplete:function(queueData){
                    console.log(queueData.uploadsSuccessful+'\n'+queueData.uploadsErrored)
                },  
            'onUploadStart':function(file){ 
             //	var params = {};
             //	$('#uploadify').uploadify('settings','formData',params);
               
            },
            'onUploadSuccess' : function(file, data, response){//Successful triggering of single file upload    
             },
             'onQueueComplete' : function(){//All files uploaded completed    
            	 alert("Upload success!");
             }    
            }); 
        //top.$("#upload").css({"z-index":"99999"});
    });  
    </script>  

  </head>
  
  <body>
   	  <div>
   	  		<span>Data sources:</span>
   	  		<input type="radio" name="bm" value="MDB" checked />MDB
   	  		<input type="radio" name="bm" value="Excel" checked />Excel
   	  </div>
   	  <table style="width: 90%;">  
            <tr>  
                <td style="width: 100px;">  
                	<form enctype="multipart/form-data">
                    <input type="file" name="uploadify" id="uploadify"/>  
                    </form>
                </td>  
                <td align="left">  
                <div id="query" onclick="javascript:$('#uploadify').uploadify('upload','*')" style="font: normal 12px Microsoft YaHei;position: absolute;top: 12px; width: 82px; right: 20px;height: 25px; line-height: 25px; border: 1px solid #0078E0; text-align: center; color: #0078E0; cursor: pointer;">
				//Start uploading
			    </div> 
			    <div id="query" onclick="javascript:$('#uploadify').uploadify('cancel','*')" style="font: normal 12px Microsoft YaHei;position: absolute;top: 12px; width: 82px; right: 120px; height: 25px; line-height: 25px; border: 1px solid #0078E0; text-align: center; color: #0078E0; cursor: pointer;">
				//Cancel upload
			    </div>
                <span id="result" style="font-size: 12px;color: #3379E2"></span>  
                </td>  
            </tr>  
        </table>  
            <div id="fileQueue" style="overflow-y: auto; position: absolute; bottom: 0px; left: 0px; right: 0px; top: 70px;"></div>  
  </body>
</html>


2. Detailed introduction:

(1)options:

$('#file_upload').uploadify({
                auto:false, 
                //Accept two values of true or false, and upload automatically when you select a file for true; when you select a file for false, only add the selected file to the queue, but not upload, then upload can only be used to trigger upload. Default to true when auto is not set
                buttonClass: "some-class", 
                //Setting the class of the upload button
                buttonCursor: 'hand',
                //Set the opening of the mouse to the button and accept two values of'hand'and'arrow' (hand and arrow)
                buttonImage: 'img/browse-btn.png', 
                //Set the path of the picture button (when your button is a picture). You can also create a hover state for the button by stacking the off-state above the hover state in the image. It's just a convenient option. The best way is to write pictures in CSS.
                buttonText: '<div>Select Files</div>',
                //Set the button text. Values are rendered as html, so they can also contain HTML tags
                checkExisting: '/uploadify/check-exists.php',
                //Accept a file path. This file checks whether the name of the file being uploaded already exists in the target directory. Return 1 when it exists, 0 when it does not exist (mainly as a background judgment), default to false
                debug: false,
                //Open or close debug mode
                fileObjName:'filedata',
                //Set the file name used by the background script. For example, in php, if this option is set to'the_files', you can use $_FILES['the_files'] to access the uploaded file.
                fileSizeLimit:'100MB',
                //Set the maximum capacity of uploaded files. This value can be a number or a string. If it is a string, accept a unit (B,KB,MB,GB). If it is a number, the default unit is KB. Setting to 0 means no restrictions
                fileTypeExts: '*.*',
                //Set file extensions (that is, file types) that allow uploads. But typing the file name manually can bypass this level of security checking, so you should always check the file type on the server side. Enter multiple extensions separated by semicolons ('*. jpg;*.png;*.gif')
                fileTypeDesc: 'All Files',
                //Description of optional files. This value appears in the file type drop-down option in the file browsing window. (Not supported under chrome, will be displayed as a'custom file', ie and firefox can display description)
                formData: {
                    timestamp: '<?php echo $timestamp;?>',
                    token: '<?php echo md5('unique_salt' . $timestamp);?>'
                },
                //When uploading files through get or post, this object provides additional data. If you want to set these values dynamically, you must use settings in the onUpload Startg event. Use $_GET or $_POST arrays (PHP) to access these values in the background script. See the official website reference: http://www.uploadify.com/documentation/uploadify/form data/
                height: 30,
                //Set the height of the button (unit px) by default to 30. (Do not write units in the value, and require an integer, as well as width)
                width: 120,
                //Set the button width (unit px), default 120
                itemTemplate:false,
                //Template object. Specify a special html template for each item added to the upload queue. For template format, see http://www.uploadify.com/documentation/uploadify/itemtemplate on the official website/
                method:'post',
                //The method of submitting uploaded files, accepting post or get values, defaults to post
                multi: false,
                //Set whether multiple files are allowed to be selected at a time, true is allowed, false is not allowed
                overrideEvents: [],
                //Rewrite the event and accept an array of event names as parameters. The set events will be overwritten by user rewriting
                preventCaching:true,
                //Whether to cache SWF files. By default, true sets a random number to the url address of SWF so that it will not be cached. (Some browsers cached swf files and could not trigger events inside -- by rainweb)
                progressData: 'percentage',
                //Set the file upload time to display data, there are two parameters `percentage'or `speed' (percentage and speed)
                queueID: false,
                //Set the ID of the DOM element of the upload queue, and the uploaded items will be added to the DOM of the ID. When set to false, the queue DOM and ID are automatically generated. Default to false
                queueSizeLimit: 999,
                //Set the number of files in each upload queue. Note that it is not a limit on the total number of upload files (that is upload Limit). If the number of files added to the queue exceeds this value, the onSelectError event will be triggered. The default value is 999
                removeCompleted: true,
                //Remove files that have been uploaded from the queue. false is not removed
                removeTimeout: 3,
                //Set the delay time for deleting files after uploading, default is 3 seconds. If removeCompleted is false, it doesn't make sense.
                requeueErrors: false,
                //Set whether files that failed to upload due to errors in the upload process will be requeued for upload
                successTimeout: 30,
                //Setting the number of seconds to wait for the server to respond after uploading a file will be considered a successful upload, defaulting to 30 seconds.
                swf: 'uploadify.swf',
                //Relative path of swf, required entry
                uploader: 'uploadify.php'
                //Server-side script file path, must write items
                uploadLimit: 999
                //The number of uploaded files. Achieving or exceeding this number triggers the onUploadError method. Default 999
            })

(2) event:


$('#file_upload').uploadify({    
                onCancel: function(file){
                        console.log('The file'+ file.name + 'was cancelled.')
                },
                //Triggered when the file is removed from the queue, returning the file parameter
                onClearQueue: function(queueItemCount){
                    console.log(queueItemCount+'file(s) were removed frome the queue')
                },
                //When the cancel method is called and the parameter'*'is passed in, the trigger is actually when the file in the entire queue is removed. The cancel method band * is said above to cancel the entire upload queue.
                onDestroy: function(){
                    //Triggered when calling the destroy method
                },
                onDialogClose: function(queueData){
                    console.log(queueData.filesSelected+'\n'+queueData.filesQueued+'\r\n'+queueData.filesReplaced+'\r\n'+queueData.filesCancelled+'\r\n'+ queueData.filesErrored)
                },
                //Triggered when the Browse File dialog box is closed. Returns the queueDate parameter with the following attributes:
                /*
                    filesSelected Number of files selected in the Browse File Dialog
                    filesQueued Number of files added to the upload queue
                    filesReplaced Number of Files Substituted
                    filesCancelled Cancel the number of files to be queued
                    filesErrored Number of files returned incorrectly
                */
                onDialogOpen:function(){
                    //Triggered when you open the Selection File dialog box
                },
                onDisable:function(){
                    //Triggered when uploadify is disabled (via the disable method)
                },
                onEnalbe: function(){
                    //Triggered when uploadify is enabled (via the disable method)
                },
                onFallback:function(){
                    //Real-time trigger when browser compatible flash version is not detected at initialization
                },
                onInit: function(instance){
                    console.log('The queue ID is'+ instance.settings.queueID)
                },
                //Triggered each time a queue is initialized, returning an instance of the uploadify object
                onQueueComplete:function(queueData){
                    console.log(queueData.uploadsSuccessful+'\n'+queueData.uploadsErrored)
                },
                //Files in the queue are uploaded and triggered, returning the queueDate parameter with the following attributes:
                /*
                    uploadsSuccessful Number of files successfully uploaded
                    uploadsErrored Number of files with errors
                */
                onSelect: function(file){
                    console.log(file.name)
                },
                //Triggered when selecting each file to add to the queue, returning the file parameter
                onSelectError: function(file,errorCode,errorMsg){
                    console.log(errorCode)
                    console.log(this.queueData.errorMsg)
                },
                //Triggered when a file error occurs and returned three parameters: file, erroCode and errorMsg.
                /*
                    errorCode A js object that contains error codes to view the error codes sent in the event to determine the specific type of error. There may be the following constants:
                    QUEUE_LIMIT_EXCEEDED:-100 The number of files selected exceeds the maximum set.
                    FILE_EXCEEDS_SIZE_LIMIT:-110 File Size Exceeding Settings
                    INVALID_FILETYPE:-130 The selected file type does not match the settings

                    errorMsg Complete error information. If you do not override the default event handler, you can use'this.queueData.errorMsg'to access the complete error information.
                */
                onSWFReady: function(){
                    //The swf animation is triggered after loading, with no parameters
                },
                onUploadComplete: function(file){
                    //Triggered after each file upload succeeds or fails, returns the uploaded file object or returns an error. If you want to know whether the upload succeeds, use the onUpload Success or onUpload Error event.
                },
                onUploadError: function(file,errorCode,erorMsg,errorString){
                },
                //Triggered when a file completes uploading but returns an error, with the following parameters
                /*
                    file File object to complete upload
                    errorCode Error code returned
                    erorMsg Error message returned
                    errorString Readable information containing all error details
                */
                onUploadProgress: function(file,bytesUploaded,bytesTotal,totalBytesUploaded,totalBytesTotal){
                    $('#pregress').html('All uploaded'+bytes Total+'bytes,'+' uploaded'+total Bytes Total+'bytes')
                },
                //Triggered every time a file upload progress is updated, the following parameters are returned
                /*
                    file Uploading File Objects
                    bytesUploaded The number of bytes a file has been uploaded
                    bytesTotal The total number of bytes of a file
                    totalBytesUploaded The total number of bytes uploaded in the current upload operation (all files)
                    totalBytesTotal Total upload bytes of all files
                */
                onUploadStart: function(file){
                    console.log('start update')
                },
                //Each file is about to be triggered before uploading
                onUploadSuccess: function(file,data,respone){
                    alert( 'id: ' + file.id
                           + ' - Indexes: ' + file.index
                + ' - file name: ' + file.name
                + ' - file size: ' + file.size
                + ' - type: ' + file.type
                + ' - Creation date: ' + file.creationdate
                + ' - modification date: ' + file.modificationdate
                + ' - File status: ' + file.filestatus
                + ' - Server-side message: ' + data
                + ' - Is uploading successful?: ' + response);
                }
                //Triggered after successful upload of each file              
})  
(3)

Methods:
Uploadify uses the plug-in pattern recommended by jquery, which means that all method calls are kept in a namespace. To call these different methods, just pass them into uploadify as the first parameter. Adding parameters after these methods will be passed into the method. method calls, simply call Uploadify on the DOM element with the method call as the first argument.Any additional arguments added after the method name are passed to the method.)

Cancel: Cancel the first uploaded file, and cancel the entire upload queue if the parameter "*" is followed, such as $(el).uploadify('cancel','*')

Upload: Upload the first uploaded file, and if the parameter "*" is followed, upload the entire queue, just like cancel

destroy: Remove upload builds and upload them by html default

disable: There are two parameters, true or false, to deny whether upload buttons are prohibited, true denotes prohibition, and false denotes permission to upload.

settings: Returns or updates the method value of an instance, accepts a parameter of a method name to return the value of that method, and updates the value of that method when followed by another parameter. as

$(el).uploadify('settings','buttonText','BROWSE'); // Set the value of buttonText to BROWSE
 $(el).uploadify('settings','buttonText') // Returns the value of buttonText

stop: stop uploading files or queues





Topics: PHP JQuery Javascript Excel