jsp+servlet+jquery 用jquery uploadify最新版本实现多文件上传

//这是script代码
        <link rel="stylesheet" type="text/css" href="uploadify/uploadify.css">
        <script type="text/javascript" src="jquery-1.8.0.js"></script>
        <script type="text/javascript" src="uploadify/jquery.uploadify.min.js"></script>
        <script>
    $(document).ready(function() {
        $('#file_upload').uploadify( {
            'debug':'true',
            'swf' : 'uploadify/uploadify.swf',//上传按钮的图片,默认是这个flash文件
            'uploader' : 'LoginServlet',//上传所处理的服务器
            'cancelImg' : 'uploadfiy/uploadify-cancel.png',//取消图片
            'method':'post',
            'folder' : '/UploadFile',//上传后,所保存文件的路径
            'queueID' : 'fileQueue',//上传显示进度条的那个div
            'buttonText' : '请选择文件',
            //'onUploadComplete': function(file){alert('The file'+file.name+'finished processing!')},//每个文件上传成功后的函数
            progressData : 'percentage',
            'auto' : false,
            'multi' : true,
            //'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)
            }
 
        });
    });
 
</script>
//这是表单元素
<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>
  1 //后台servlet
  2 package com.accp.upload;
  3 import java.io.BufferedInputStream;
  4 import java.io.BufferedOutputStream;
  5 import java.io.File;
  6 import java.io.FileOutputStream;
  7 import java.io.IOException;
  8 import java.io.PrintWriter;
  9 import java.text.SimpleDateFormat;
 10 import java.util.Date;
 11 import java.util.Iterator;
 12 import java.util.List;
 13  
 14 import javax.servlet.ServletException;
 15 import javax.servlet.http.HttpServlet;
 16 import javax.servlet.http.HttpServletRequest;
 17 import javax.servlet.http.HttpServletResponse;
 18  
 19 import org.apache.commons.fileupload.disk.DiskFileItem;
 20 import org.apache.commons.fileupload.disk.DiskFileItemFactory;
 21 import org.apache.commons.fileupload.servlet.ServletFileUpload;
 22 import org.apache.commons.fileupload.util.Streams;
 23  
 24 public class LoginServlet extends HttpServlet {
 25  
 26     /**
 27      * The doGet method of the servlet. <br>
 28      * 
 29      * This method is called when a form has its tag value method equals to get.
 30      * 
 31      * @param request
 32      *            the request send by the client to the server
 33      * @param response
 34      *            the response send by the server to the client
 35      * @throws ServletException
 36      *             if an error occurred
 37      * @throws IOException
 38      *             if an error occurred
 39      */
 40     public void doGet(HttpServletRequest request, HttpServletResponse response)
 41             throws ServletException, IOException {
 42  
 43         response.setContentType("text/html;charset=utf-8;");
 44         doPost(request, response);
 45     }
 46  
 47     /**
 48      * The doPost method of the servlet. <br>
 49      * 
 50      * This method is called when a form has its tag value method equals to
 51      * post.
 52      * 
 53      * @param request
 54      *            the request send by the client to the server
 55      * @param response
 56      *            the response send by the server to the client
 57      * @throws ServletException
 58      *             if an error occurred
 59      * @throws IOException
 60      *             if an error occurred
 61      */
 62     @SuppressWarnings("unchecked")
 63     public void doPost(HttpServletRequest request, HttpServletResponse response)
 64             throws ServletException, IOException {
 65  
 66         response.setContentType("text/html;charset=utf-8;");
 67         request.setCharacterEncoding("utf-8");
 68         PrintWriter out = response.getWriter();
 69         // 设置接收的编码格式
 70         request.setCharacterEncoding("UTF-8");
 71         Date date = new Date();// 获取当前时间
 72         SimpleDateFormat sdfFileName = new SimpleDateFormat("yyyyMMddHHmmss");
 73         SimpleDateFormat sdfFolder = new SimpleDateFormat("yyMM");
 74         String newfileName = sdfFileName.format(date);// 文件名称
 75         String fileRealPath = "";// 文件存放真实地址
 76  
 77         String fileRealResistPath = "";// 文件存放真实相对路径
 78  
 79         // 名称 界面编码 必须 和request 保存一致..否则乱码
 80         String name = request.getParameter("name");
 81  
 82         String firstFileName = "";
 83         // 获得容器中上传文件夹所在的物理路径
 84         String savePath = this.getServletConfig().getServletContext()
 85                 .getRealPath("/")
 86                 + "uploads\" + newfileName + "\";
 87         System.out.println("路径" + savePath + "; name:" + name);
 88         File file = new File(savePath);
 89         if (!file.isDirectory()) {
 90             file.mkdirs();
 91         }
 92  
 93         try {
 94             DiskFileItemFactory fac = new DiskFileItemFactory();
 95             ServletFileUpload upload = new ServletFileUpload(fac);
 96             upload.setHeaderEncoding("UTF-8");
 97             // 获取多个上传文件
 98             List fileList = fileList = upload.parseRequest(request);
 99             // 遍历上传文件写入磁盘
100             Iterator it = fileList.iterator();
101             while (it.hasNext()) {
102                 Object obit = it.next();
103                 if (obit instanceof DiskFileItem) {
104                     System.out.println("xxxxxxxxxxxxx");
105                     DiskFileItem item = (DiskFileItem) obit;
106  
107                     // 如果item是文件上传表单域
108                     // 获得文件名及路径
109                     String fileName = item.getName();
110                     if (fileName != null) {
111                         firstFileName = item.getName().substring(
112                                 item.getName().lastIndexOf("\") + 1);
113                         String formatName = firstFileName
114                                 .substring(firstFileName.lastIndexOf("."));// 获取文件后缀名
115                         fileRealPath = savePath + newfileName + formatName;// 文件存放真实地址
116  
117                         BufferedInputStream in = new BufferedInputStream(item
118                                 .getInputStream());// 获得文件输入流
119                         BufferedOutputStream outStream = new BufferedOutputStream(
120                                 new FileOutputStream(new File(fileRealPath)));// 获得文件输出流
121                         Streams.copy(in, outStream, true);// 开始把文件写到你指定的上传文件夹
122                         // 上传成功,则插入数据库
123                         if (new File(fileRealPath).exists()) {
124                             // 虚拟路径赋值
125                             fileRealResistPath = sdfFolder.format(date)
126                                     + "/"
127                                     + fileRealPath.substring(fileRealPath
128                                             .lastIndexOf("\") + 1);
129                             // 保存到数据库
130                             System.out.println("保存到数据库:");
131                             System.out.println("name:" + name);
132                             System.out.println("虚拟路径:" + fileRealResistPath);
133                         }
134  
135                     }
136                 }
137             }
138         } catch (org.apache.commons.fileupload.FileUploadException ex) {
139             ex.printStackTrace();
140             System.out.println("没有上传文件");
141             return;
142         }
143         response.getWriter().write("1");
144         out.flush();
145         out.close();
146  
147     }
148  
149 }

原文地址:https://www.cnblogs.com/lr393993507/p/5286610.html