首页 > 代码库 > java 上传2(使用java组件fileupload和uploadify)

java 上传2(使用java组件fileupload和uploadify)

项目关键包和插件

插件地址:http://www.uploadify.com/documentation

 

项目结构

 

uploadify.css设置了cancel的图片路径这里修改一下

 

 

 

 

uploadify.jsp

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://"
            + request.getServerName() + ":" + request.getServerPort()
            + path + "/";
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<base href="http://www.mamicode.com/">
<title>uploadify</title>
<link href="http://www.mamicode.com/css/uploadify.css" rel="stylesheet"type="text/css"/>

<style type="text/css">
#some_file_queue {
    background-color: #FFF;
    border-radius: 3px;
    box-shadow: 0 1px 3px rgba(0,0,0,0.25);
    height: 103px;
    margin-bottom: 10px;
    overflow: auto;
    padding: 5px 10px;
    width: 300px;
}
</style>

<script type="text/javascript" src="http://www.mamicode.com//js/jquery-1.6.2.js"></script>
<script type="text/javascript" src="http://www.mamicode.com//js/jquery.uploadify.min.js"></script>
<script type="text/javascript">  

// http://www.uploadify.com/documentation/
        $(function() {  
            $(‘#file_upload‘).uploadify({
                ////接受true or false两个值,当为true时选择文件后会自动上传;为false时只会把选择的文件增加进队列但不会上传,这时只能使用upload的方法触发上传。不设置
                ‘auto‘     : false,
                
                //falsh路径
                ‘swf‘      :  ‘<%=basePath%>‘+‘/css/uploadify.swf‘,
                
                //上传到服务器
                
                ‘uploader‘ :‘<%=basePath%>‘+‘/upload/unloadifyU‘,
                
                //XX图片
                //‘cancelImg‘ :  ‘<%=basePath%>‘+‘/css/uploadify-cancel.png‘,
                
                //The maximum size allowed for a file upload.  This value can be a number or string.  If it’s a string, it accepts a unit (B, KB, MB, or GB).  The default unit is in KB.  You can set this value to 0 for no limit.
                //设置上传文件的容量最大值。这个值可以是一个数字或者字符串。如果是字符串,接受一个单位(B,KB,MB,GB)。如果是数字则默认单位为KB。设置为0时表示不限制
                ‘fileSizeLimit‘ : ‘100000KB‘,
                
                //The maximum number of files that can be in the queue at one time.  This does not limit the number of files that can be uploaded.  To limit the number of files that can be uploaded, use uploadLimit.  If the number of files selected to add to the queue exceeds this limit, the <onSelectError> event is triggered.Default Value999
                //设置每一次上传队列中的文件数量。注意并不是限制总的上传文件数量(那是uploadLimit).如果增加进队列中的文件数量超出这个值,将会触发onSelectError事件。默认值为999
                //queueSizeLimit等 可触发onSelectError
                ‘queueSizeLimit‘ : 1,
                

                //The maximum number of files you are allowed to upload.  When this number is reached or exceeded, the <onUploadError> event is triggered.Default Value999
                //uploadLimit等 可触发onUploadError
                //允许上传多少个,除非重新刷新
                ‘uploadLimit‘ : 10,

                             
                //Default Value‘*.*‘   (i.e. ‘*.jpg; *.png; *.gif’).
                //设置允许上传的文件扩展名(也就是文件类型)。但手动键入文件名可以绕过这种级别的安全检查,所以你应该始终在服务端中检查文件类型。输入多个扩展名时用分号隔开(‘*.jpg;*.png;*.gif‘)
                ‘fileTypeExts‘ : ‘*.txt;*.sql;*.gif; *.jpg; *.png‘,
                
                //An object containing additional data to send via get or post with each file upload.  If you plan on setting these values dynamically, this should be done using the ‘settings’ method in the onUploadStart event.  You can access these values in the server-side script using the $_GET or $_POST arrays (PHP).
                //通过get或post上传文件时,此对象提供额外的数据。如果想动态设置这些值,必须在onUploadStartg事件中使用settings的方法设置。在后台脚本中使用 $_GET or $_POST arrays (PHP)存取这些值。看官网参考写法:http://www.uploadify.com/documentation/uploadify/formdata/
                ‘formData‘      : {‘id‘ : "1", ‘idd‘ : 1111},
                //也可这样onUploadStart动态设置值
                
                //Set to false to keep files that have completed uploading in the queue. Default Value true
                //是否移除掉队列中已经完成上传的文件。false为不移除
                ‘removeCompleted‘ : false,
                
                //The delay in seconds before a completed upload is removed from the queue.Default Value 3
                ////设置上传完成后删除掉文件的延迟时间,默认为3秒。如果removeCompleted为false的话,就没意义
                //‘removeTimeout‘ : 3,
                
                ////提交上传文件的方法,接受post或get两个值,默认为post
                ‘method‘   : ‘post‘,
                
                //Set to false to allow only one file selection at a time.Default Value true
                //设置是否允许一次选择多个文件,true为允许,false不允许
                //‘multi‘    : false,
                
                //The ID (without the hash) of a DOM element to use as the file queue.  File queue items will be appended directly to this element if defined.  If this option is set to false, a file queue will be generated and the queueID option will be dynamically set.Default Value false
                //设置上传队列DOM元素的ID,上传的项目会增加进这个ID的DOM中。设置为false时则会自动生成队列DOM和ID。默认为false
                //‘queueID‘  : ‘some_file_queue‘,
                
            
                //If set to true, a random value is added to the SWF file URL so it doesn’t cache.  This will conflict with any existing querystring parameters on the SWF file URL.Default Value true
                ////是否缓存swf文件。默认为true,会给swf的url地址设置一个随机数,这样它就不会被缓存。(有些浏览器缓存了swf文件就会触发不了里面的事件--by rainweb)
                //‘preventCaching‘ : true,
                
                //Set what type of data to display in the queue item during file upload progress updates.  The two options are ‘percentage’ or ‘speed’.
                //Default Value‘percentage‘
                //‘progressData‘ : ‘speed‘,
                
                //The time in seconds to wait for the server’s response when a file has completed uploading.  After this amount of time, the SWF file will assume success.Default Value30
                //设置文件上传后等待服务器响应的秒数,超出这个时间,将会被认为上传成功,默认为30秒
                //‘successTimeout‘ : 5,
                
                //If set to true, files that return errors during an upload are requeued and the upload is repeatedly tried.Default Valuefalse
                //设置上传过程中因为出错导致上传失败的文件是否重新加入队列中上传
                ‘requeueErrors‘ : false,
                
                
                //The name of the file object to use in your server-side script.  For example, in PHP, if this option is set to ‘the_files’, you can access the files that have been uploaded using $_FILES[‘the_files‘];
              //设置在后台脚本使用的文件名。举个例子,在php中,如果这个选项设置为‘the_files‘,你可以使用$_FILES[‘the_files‘]存取这个已经上传的文件。
                //‘fileObjName‘ : ‘the_files‘,
                
                
                //button height,Default Value 30
                ////设置按钮的高度(单位px),默认为30.(不要在值里写上单位,并且要求一个整数,width也一样)
                //‘height‘   : 50,
                
                //button width,Default Value 120
                ////设置按钮宽度(单位px),默认120
                //‘width‘    : 300,
                
                //The description of the selectable files.  This string appears in the browse files dialog box in the file type drop down.
                //弹出窗口时候右边选择类型的描叙,意义不大
                //‘fileTypeDesc‘ : ‘Any old file you want...‘,
                
                //debug模式
                //‘debug‘    : false,
                
                ////设置上传按钮的class
                //‘buttonClass‘:‘‘,
                
                //设置图片按钮的路径(当你的按钮是一张图片时)。如果使用默认的样式,你还可以创建一个鼠标悬停状态,但要把两种状态的图片放在一起,并且默认的放上面,悬停状态的放在下面(原文好难表达啊:you can create a hover state for the button by stacking the off state above the hover state in the image)。这只是一个比较便利的选项,最好的方法还是把图片写在CSS里面
                //‘buttonImage‘:‘‘,
                
                 ////设置按钮文字。值会被当作html渲染,所以也可以包含html标签
                //buttonText: ‘<div>选择文件</div>‘
                
                //The script should return 1 if the file name exists or 0 if the file name does not exist.
                ////接受一个文件路径。此文件检查正要上传的文件名是否已经存在目标目录中。存在时返回1,不存在时返回0(应该主要是作为后台的判断吧),默认为false
                //‘checkExisting‘ : ‘/uploadify/check-exists.php‘,
                
                ////设置鼠标移到按钮上的开状,接受两个值‘hand‘和‘arrow‘(手形和箭头)默认是hand
                //‘buttonCursor‘ : ‘arrow‘,
                
                //An array of event names for which you would like to bypass the default scripts for.  You can tell which events can be overridden on the documentation page for each event.
                //Default ValueEmpty Array
                ////重写事件,接受事件名称的数组作为参数。所设置的事件将可以被用户重写覆盖
                //‘overrideEvents‘ : [‘onUploadProgress‘],  
                
                
                 //itemTemplate:The itemTemplate option allows you to specify a special HTML template for each item that is added to the queue.           
                //‘itemTemplate‘ : ‘‘,
                
                
                
                
                
                
                         
                //事件
                
                
                   //Triggered when a file is removed from the queue (but not if it’s replaced during  a select operation).
                onCancel: function(file){
                        alert(file.name+":cancle");
                },
                
                //文件被移除出队列时触发,返回file参数
                onClearQueue: function(queueItemCount){
                    //console.log(queueItemCount+‘file(s) were removed frome the queue‘);
                },
                
                
                onDestroy: function(){
                    //调用destroy方法的时候触发
                },
                
                //打开选择文件对话框时触发
                onDialogOpen:function(){
                    //console.log(‘OPEN dialog‘);
                },
                
                //关闭掉浏览文件对话框时触发。返回queueDate参数,有以下属性:
                /*
                    filesSelected 浏览文件对话框中选取的文件数量
                    filesQueued 加入上传队列的文件数
                    filesReplaced 被替换的文件个数
                    filesCancelled 取消掉即将加入队列中的文件个数
                    filesErrored 返回错误的文件个数
                */
                onDialogClose: function(queueData){
                    //console.log(queueData.filesSelected+‘\n‘+queueData.filesQueued+‘\r\n‘+queueData.filesReplaced+‘\r\n‘+queueData.filesCancelled+‘\r\n‘+ queueData.filesErrored)
                },
                
                onDisable:function(){
                    //禁用uploadify时触发(通过disable方法)
                },
                onEnalbe: function(){
                    //启用uploadify时触发(通过disable方法)
                },
                
                
               //每次初始化一个队列时触发,返回uploadify对象的实例
                onInit: function(instance){
                    //console.log(‘The queue ID is:‘+ instance.settings.queueID);
                },
                
                onSWFReady: function(){
                    //swf动画加载完后触发,没有参数
                    //console.log(‘SWF IS READDY‘);
                },
                
                onFallback:function(){
                    //在初始化时检测不到浏览器有兼容性的flash版本时实触发
                    alert("init false error");
                },
                
                
              //选择每个文件增加进队列时触发,返回file参数
                onSelect: function(file){
                    //console.log("onSelect:::"+file.name);
                },
                
                /*
                errorCode是一个包含了错误码的js对象,用来查看事件中发送的错误码,以确定错误的具体类型,可能会有以下的常量:
                QUEUE_LIMIT_EXCEEDED:-100 选择的文件数量超过设定的最大值;
                FILE_EXCEEDS_SIZE_LIMIT:-110 文件的大小超出设定
                INVALID_FILETYPE:-130 选择的文件类型跟设置的不匹配

                errorMsg 完整的错误信息,如果你不重写默认的事件处理器,可以使用‘this.queueData.errorMsg’ 存取完整的错误信息
                */
                onSelectError: function(file,errorCode,errorMsg){
                    //console.log(errorCode);
                    //console.log(this.queueData.errorMsg);
                },
                
                
              //每个文件即将上传前触发
                ‘onUploadStart‘ : function(file) {
                    $("#file_upload").uploadify("settings", "formData", {"someOtherKey":1111111});
                },
                
              //每个文件上传成功后触发 ,可根据服务器返回data字段进行下一步
                onUploadSuccess: function(file,data,respone){
                    alert( ‘id: ‘ + file.id+ ‘ - 索引: ‘ + file.index
                    + ‘ - 文件名: ‘ + file.name
                    + ‘ - 文件大小: ‘ + file.size
                    + ‘ - 类型: ‘ + file.type
                    + ‘ - 创建日期: ‘ + file.creationdate
                    + ‘ - 修改日期: ‘ + file.modificationdate
                    + ‘ - 文件状态: ‘ + file.filestatus
                    + ‘ - 服务器端消息: ‘ + data
                    + ‘ - respone: ‘ + respone);
                },
                
                          
                //一个文件完成上传但返回错误时触发,有以下参数
                /*
                    file 完成上传的文件对象
                    errorCode 返回的错误代码
                    erorMsg 返回的错误信息
                    errorString 包含所有错误细节的可读信息
                */
                onUploadError: function(file,errorCode,erorMsg,errorString){
                },
                
                
                
                
                
                onUploadComplete: function(file){
                    //在每一个文件上传成功或失败之后触发,返回上传的文件对象或返回一个错误,如果你想知道上传是否成功,最后使用onUploadSuccess或onUploadError事件
                },
                
                
                //每更新一个文件上传进度的时候触发,返回以下参数
                /*
                    file 正上传文件对象
                    bytesUploaded 文件已经上传的字节数
                    bytesTotal 文件的总字节数
                    totalBytesUploaded 在当前上传的操作中(所有文件)已上传的总字节数
                    totalBytesTotal 所有文件的总上传字节数
                */
                onUploadProgress: function(file,bytesUploaded,bytesTotal,totalBytesUploaded,totalBytesTotal){
                    $(‘#pregress‘).html(‘<span>总共需要上传‘+bytesTotal+‘字节,‘+‘已上传‘+totalBytesTotal+‘字节</span>‘);
                },
                
                
                
                
                
                //队列中的文件都上传完后触发,返回queueDate参数,有以下属性:
                /*
                    uploadsSuccessful 成功上传的文件数量
                    uploadsErrored 出现错误的文件数量
                */
                onQueueComplete:function(queueData){
                    console.log("onQueueComplete::::::"+queueData.uploadsSuccessful+‘\n‘+queueData.uploadsErrored);
                },
                
                
                
                
            });  
            
                 
            
        });  
        
        function changeBtnText() {
            $(‘#file_upload‘).uploadify(‘settings‘,‘buttonText‘,‘BROWSE‘);
        }
        function returnBtnText() {
            alert(‘The button says ‘ + $(‘#file_upload‘).uploadify(‘settings‘,‘buttonText‘));
        }

</script>
 

</head>

  <body>
<form>  

<input type="text" name="xxxxxxxxx" />

<div id="some_file_queue"></div>

<div id="pregress"></div>
    <input type="file" name="file_upload" id="file_upload" />
<br/>
    <div>
    <a href="javascript:$(‘#file_upload‘).uploadify(‘cancel‘)">Cancel First File</a> | <a href="javascript:$(‘#file_upload‘).uploadify(‘cancel‘, ‘*‘)">Clear the Queue</a>
   </div>
<br/>   
   <div>
   <a href="javascript:$(‘#file_upload‘).uploadify(‘destroy‘)">Destroy Uploadify</a>
   </div>
<br/>   
   <div>
   <a href="javascript:$(‘#file_upload‘).uploadify(‘disable‘, true)">Disable the Button</a> | <a href="javascript:$(‘#file_upload‘).uploadify(‘disable‘, false)">Enable the Button</a>
   </div>
<br/>   
   <div>
   <a href="javascript:$(‘#file_upload‘).uploadify(‘upload‘,‘*‘)">Upload Files</a>
   </div>
<br/>   
   <div>
    <a href="javascript:$(‘#file_upload‘).uploadify(‘stop‘)">Stop the Uploads!</a>
   </div>
   <br/>
     
   <div>
   <a href="javascript:changeBtnText()">Change the Button Text</a> | <a href="javascript:returnBtnText();">Read the Button</a>
   </div>
   
</form>
  </body>
</html>

 

 

后台程序

    @RequestMapping(value="http://www.mamicode.com/unloadify")
    public String unloadify(HttpServletRequest request,HttpServletResponse response){       
        return "/unloadify";
    }
    
    
    @RequestMapping(value="http://www.mamicode.com/unloadifyU",method=RequestMethod.POST)
    public void unloadifyU(HttpServletRequest request,HttpServletResponse response) throws FileUploadException, Exception{
        
        Map<String,String> map = new HashMap<String,String>();
        PrintWriter out = response.getWriter();
        
      //这样获取不到unloadify中设置formData的值,要通过下面方法取(getFieldName,getString),和form中name的值(因为不是form提交)
        String id=request.getParameter("id");
        String idd=request.getParameter("idd");  
        String someOtherKey=request.getParameter("someOtherKey");
        String xxxxxxxxx=request.getParameter("xxxxxxxxx");
        
        File uploadPath = new File("D:\\temp");//上传文件目录
        if (!uploadPath.exists()) {
           uploadPath.mkdirs();
        }
        // 临时文件目录
        File tempPathFile = new File("d:\\temp\\buffer\\");
        if (!tempPathFile.exists()) {
           tempPathFile.mkdirs();
        }
        try {
           DiskFileItemFactory factory = new DiskFileItemFactory();
           factory.setSizeThreshold(4096); // 设置缓冲区大小,这里是4kb
           factory.setRepository(tempPathFile);//设置缓冲区目
           ServletFileUpload upload = new ServletFileUpload(factory);    
           upload.setSizeMax(41943040); // 设置最大文件尺寸,这里是40MB
     
           List<FileItem> items = upload.parseRequest(request);//得到所有的文件
           Iterator<FileItem> i = items.iterator();
           while (i.hasNext()) {
               FileItem fi = (FileItem) i.next();           
               if(fi.isFormField()){//如果是普通的表单字段           
                   //获取unloadify中设置formData的值,而不是form的值,因为不是form提交所以xxxxxxxxx读取不到
                   String fieldName = fi.getFieldName();
                   System.out.println(" name is:" + fi.getFieldName()+"-value:"+ fi.getString());//显示表单内容。
                   
               }else{//如果是上传文件,显示文件名。
                   String fileName = fi.getName();
                   if (fileName != null) {                     
                       //检查文件后缀格式  
                   String fileEnd = fileName.substring(fileName.lastIndexOf(".")+1).toLowerCase();                   
                   List<String> extList=new ArrayList<String>();//ext后缀校验
                   extList.add("sql");
                   extList.add("txt");
                     if(extList.contains(fileEnd)){
                         File fullFile = new File(fi.getName());
                         File savedFile = new File(uploadPath, fullFile.getName());
                         fi.write(savedFile);
                     }else{
                            map.put("res", "1");
                         System.out.print("ext error");
                     }               
                   }
               }
           }
           map.put("res", "0");
           System.out.print("upload succeed");
        }  catch (Exception e) {
            e.printStackTrace();
         }

        JSONObject jsonObject = JSONObject.fromObject(map);
        String msg =  jsonObject.toString();
        out.print(msg);
        out.close();
    }

 

java 上传2(使用java组件fileupload和uploadify)