jquery uploadify多文件上传

项目中使用

1、下载相关jar 包:commons-fileupload-1.2.2.jar,commons-io-2.1.jar,commons-logging-1.1.1.jar

2、jsp页面

1、首先jsp页面引入的文件

   <link href="js/uploadify.css" rel="stylesheet" type="text/css" />  
  <script type="text/javascript" src="js/jquery-1.4.4.min.js"></script>  
<script type="text/javascript" src="scripts/swfobject.js"></script>  
<script type="text/javascript" src="js/jquery.uploadify.min.js"></script>  
<!--ready事件-->  
<script type="text/javascript">  
 $(document).ready(function() {
    $('#file_upload').uploadify( {  
      //  'debug':'true',  
        'swf'            : '<%=path%>/js/uploadify.swf',  
        'uploader'       : '<%=path%>/Upload',//后台处理的请求  
        'cancelImg'      : '<%=path%>js/uploadify-cancel.png',
        'method':'post',  
        'folder' : '/UploadFile',//上传后,所保存文件的路径  
        'queueID' : 'fileQueue',//上传显示进度条的那个div  
        'buttonText' : '请选择文件',  
        'onUploadComplete': function(file){
            alert(file.id)
            alert('The file'+file.name+'finished processing!')},//每个文件上传成功后的函数  
        progressData : 'percentage',  //设置上传进度显示方式,percentage显示上传百分比,speed显示上传速度
       // progressData : 'speed',  
        'auto' : true,  
        'multi' : true,  
        'removeCompleted':false,//是否自动将已完成任务从队列中删除,如果设置为false则会一直保留此任务显示
        //'onSelect':function(file){  
        //alert("文件"+file.name+"被选择了!");  
        //}  
        //'onQueueComplete' : function(queueData) {  
        //  alert(queueData.filesQueued + 'files were successfully!')  
        //},//当队列中的所有文件上传成功后,弹出共有多少个文件上传成功  
        'onDisable' : function() {  
            alert('uploadify is disable');  
        },//在调用disable方法时候触发  
        //'onCancel':function(){alert('你取消了文件上传')}  
        //'onUploadStart' : function(file) {//在调用上传前触发  
        //alert('The file ' + file.name + ' is being uploaded.')}  
        'onError' : function(errorType,errObj) {  
            alert('The error was: ' + errObj.info)  
        }  

    });  
   }); 

   <body>  
        <!--   <div id="fileQueue"></div>  
            <input type="file" name="uploadify" id="uploadify" />  
            <p>  
                <a href="javascript:$('#uploadify').uploadify('upload')">开始上传</a>   
                <a href="javascript:$('#uploadify').uplaodify('cancel','*')">取消上传</a>  
            </p>   -->
            <div id="fileQueue"></div>  
        <input id="file_upload" name="file_upload" type="file" multiple="true">  
        <p>  
            <!-- 加上“*”表示当第一个文件上传成功后,立即上传以后队列中的文件,否则需要自己手动 -->  
            <a href="javascript:$('#file_upload').uploadify('upload','*')">上传</a>|  
            <a  
                href="javascript:$('#file_upload').uploadify('cancel',$('.uploadifive-queue-item').first().data('file'))">取消上传</a>  
            <a href="javascript:$('#file_upload').uploadify('cancel','*')">清空所有的上传文件</a>  
            <a href="javascript:$('#file_upload').uploadify('stop','*')">暂停</a>  
            <!-- 如果填入true则表示禁用上传按钮 -->  
            <a href="javascript:$('#file_upload').uploadify('disable','true')">禁用</a>  
            <a href="javascript:$('#file_upload').uploadify('debug')">调试</a>  
        </p>  
            
    </body> 

3、servlet

package com.yun4j;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.disk.DiskFileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.util.Streams;

/**
 * Servlet implementation class Upload
 */
public class Upload extends HttpServlet implements Servlet {
      private static final long serialVersionUID = 1L;    
      
        /**  
         * 实现多文件的同时上传  
         */     
        public void doGet(HttpServletRequest request,    
                HttpServletResponse response) throws ServletException, IOException {    
                
            //设置接收的编码格式    
            request.setCharacterEncoding("UTF-8");    
            Date date = new Date();//获取当前时间    
            SimpleDateFormat sdfFileName = new SimpleDateFormat("yyyyMMddHHmmss");    
            SimpleDateFormat sdfFolder = new SimpleDateFormat("yyMM");    
            String newfileName = sdfFileName.format(date);//文件名称    
            String fileRealPath = "";//文件存放真实地址    
                
            String fileRealResistPath = "";//文件存放真实相对路径    
                
            //名称  界面编码 必须 和request 保存一致..否则乱码    
            String name = request.getParameter("name");    
                    
                 
            String firstFileName="";    
            // 获得容器中上传文件夹所在的物理路径    
            String savePath = this.getServletConfig().getServletContext().getRealPath("/") + "uploads\\" + newfileName +"\\";    
            System.out.println("路径" + savePath+"; name:"+name);    
            File file = new File(savePath);    
            if (!file.isDirectory()) {    
                file.mkdirs();    
            }    
        
            try {    
                DiskFileItemFactory fac = new DiskFileItemFactory();    
                ServletFileUpload upload = new ServletFileUpload(fac);    
                upload.setHeaderEncoding("UTF-8");    
                // 获取多个上传文件    
                List fileList = fileList = upload.parseRequest(request);    
                // 遍历上传文件写入磁盘    
                Iterator it = fileList.iterator();    
                while (it.hasNext()) {    
                    Object obit = it.next();  
                    if(obit instanceof DiskFileItem){  
                        System.out.println("xxxxxxxxxxxxx");  
                        DiskFileItem item = (DiskFileItem) obit;    
                            
                        // 如果item是文件上传表单域       
                        // 获得文件名及路径       
                        String fileName = item.getName();    
                        if (fileName != null) {    
                            firstFileName=item.getName().substring(item.getName().lastIndexOf("\\")+1);    
                            String formatName = firstFileName.substring(firstFileName.lastIndexOf("."));//获取文件后缀名    
                            fileRealPath = savePath + newfileName+ formatName;//文件存放真实地址    
                                
                            BufferedInputStream in = new BufferedInputStream(item.getInputStream());// 获得文件输入流    
                            BufferedOutputStream outStream = new BufferedOutputStream(new FileOutputStream(new File(fileRealPath)));// 获得文件输出流    
                            Streams.copy(in, outStream, true);// 开始把文件写到你指定的上传文件夹    
                            //上传成功,则插入数据库    
                            if (new File(fileRealPath).exists()) {    
                                //虚拟路径赋值    
                                fileRealResistPath=sdfFolder.format(date)+"/"+fileRealPath.substring(fileRealPath.lastIndexOf("\\")+1);    
                                //保存到数据库    
                                System.out.println("保存到数据库:");    
                                System.out.println("name:"+name);    
                                System.out.println("虚拟路径:"+fileRealResistPath);    
                            }    
                                 
                        }     
                    }  
                }     
            } catch (org.apache.commons.fileupload.FileUploadException ex) {  
               ex.printStackTrace();    
               System.out.println("没有上传文件");    
               return;    
            }     
           response.getWriter().write("1");    
                
        }    
         
        public void doPost(HttpServletRequest req, HttpServletResponse resp)    
                throws ServletException, IOException {    
            doGet(req, resp);    
        }    
}
4、web.xml

  <servlet>
    <description></description>
    <display-name>Upload</display-name>
    <servlet-name>Upload</servlet-name>
    <servlet-class>com.yun4j.Upload</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>Upload</servlet-name>
    <url-pattern>/Upload</url-pattern>
  </servlet-mapping>

posted @ 2016-04-14 10:49  赤子之心_timefast  阅读(302)  评论(0编辑  收藏  举报