Java调用uploadify实现文件上传Demo实现

原创
2013/11/01 17:08
阅读数 6.2W

导读:uploadify是来自国外的一款优秀的基于jQuery的文件上传插件,主要功能是批量上传文件,此插件在项目中已被广泛之用,于是决定花点时间搞了一个基于Java语言的demo,特此公布出来。

一、采用版本及页面基本引入介绍

本demo采用的是uploadify的2.1.0版本,下载地址:http://download.csdn.net/detail/zengzhuangjun/4340007

我们需要在html页面的<head></head>标签中加入如下代码:
  <link href="/res/plugin/uploadify/uploadify.css" rel="stylesheet" type="text/css" />
  <script type="text/javascript" src="/res/plugin/uploadify/jquery-1.3.2.min.js"></script>
  <script type="text/javascript" src="/res/plugin/uploadify/swfobject.js"></script>
  <script type="text/javascript" src="/res/plugin/uploadify/jquery.uploadify.v2.1.0.js"></script>

二、uploadify页面初始化

1、在页面需要展示的上传的地方加入如下代码:
  <table>
        <tr>
            <td><label><img src="/images/save.gif"/> 上传课件:</label></td>
            <td><label><input type="file" name="uploadify" id="uploadify"/></label>&nbsp;&nbsp;</td>
            <td><div id="fileQueue"></div></td>
        </tr>
   </table>
注意:代码中的<input type="file" name="uploadify" id="uploadify"/> 和<div id="fileQueue"></div>不可缺少,主要是用来显示浏览文件的flash'文件盒上传进度的显示。

2、初始化上传组件:
$(document).ready(function(){
       $("#uploadify").uploadify({
            'uploader': '/res/plugin/uploadify/uploadify.swf',
            'script':"/fileserver/upload",
            'cancelImg': '/res/plugin/uploadify/cancel.png',
            'queueID': 'fileQueue',
            'auto': true,
            'buttonText': 'select',
            'simUploadLimit' : 1,
            'queueSizeLimit' : 1,
            'fileExt': '*.jpg;*.gif;*.jpeg;*.png;*.bmp;*.zip;*.rar;*.7z',
            onComplete: function(event, queueID, fileObj, response, data) {
                //转换为json对象
                var dataObj = eval("("+response+")");
                saveFile(dataObj);
            },
            onSelect:function(){
            },
            onError: function(event, queueID, fileObj) {
                alert("文件:" + fileObj.name + "上传失败");
            }
        });
});

三、uploadify上传处理的Java代码

1、上传servlet代码:

这里我们使用Servlet来实现文件的上传处理,参考代码:
import com.poweree.util.DateUtils;
import net.sf.json.JSONObject;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * User: http://www.mbaike.net
 * Date: 13-10-31
 * Time: 下午4:31
 * To change this template use File | Settings | File Templates.                                   a
 */
public class FileServlet extends HttpServlet {

    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Map map = new HashMap();
        request.setCharacterEncoding("utf-8");
        DiskFileItemFactory factory = new DiskFileItemFactory();
        String path = request.getRealPath("/file");
        factory.setRepository(new File(path));
        factory.setSizeThreshold(1024*1024) ;
        ServletFileUpload upload = new ServletFileUpload(factory);
        try {
            //可以上传多个文件
            List<FileItem> list = (List<FileItem>)upload.parseRequest(request);
            for(FileItem item : list){
                if(!item.isFormField()){
                    String name = item.getName() ;
                    String fileSuffix  = name.substring(name.lastIndexOf(".")+1,name.length());
                    String oldName = name.replaceAll("." + fileSuffix,"");
                    String fileName = DateUtils.getNowTime(DateUtils.DATE_All_KEY_STR);
                    String newName = fileName + "." + fileSuffix;
                    OutputStream out = new FileOutputStream(new File(path,newName));
                    InputStream in = item.getInputStream() ;
                    int length = 0 ;
                    byte [] buf = new byte[1024] ;
                    while( (length = in.read(buf) ) != -1){
                        out.write(buf, 0, length);
                    }
                    in.close();
                    out.close();
                    /**将上传处理后的数据返回**/
                    map.put("fileSuffix",fileSuffix);
                    map.put("fileName",oldName);
                    map.put("filePath",fileName);
                    break;
                }
            }
        }catch (Exception e) {
            System.out.println("出错了:" + e.getMessage());
        }
        response.setContentType("text/xml; charset=UTF-8");
        response.setHeader("Cache-Control", "no-cache");
        response.setHeader("Pragma", "no-cache");
        PrintWriter out = response.getWriter();
        JSONObject jsonObject = JSONObject.fromObject(map);
        String msg =  jsonObject.toString();
        out.print(msg);
        out.close();
    }

    public void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        doPost(req, resp);
    }
}

代码中的String fileName = DateUtils.getNowTime(DateUtils.DATE_All_KEY_STR); 主要是为了生成文件的唯一名称(日期标记)

2、在web.xml配置servlet:

    <servlet>
        <description>FileServlet</description>
        <display-name>FileServlet</display-name>
        <servlet-name>FileServlet</servlet-name>
        <servlet-class>com.test.fileserver.utils.FileServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>FileServlet</servlet-name>
        <url-pattern>/fileserver/upload</url-pattern>
    </servlet-mapping>

四、截图:

 




 

uploadify的下载和详细介绍,详见:http://www.mbaike.net/techs/1938.html

展开阅读全文
打赏
0
16 收藏
分享
加载中

引用来自“思维80”的评论

String fileName = DateUtils.getNowTime(DateUtils.DATE_All_KEY_STR); 里面的DATE_All_KEY_STR报错,请问你import com.poweree.util.DateUtils; 引入的是啥jar包呢?
他有写注释,他自己写的 代码中的String fileName = DateUtils.getNowTime(DateUtils.DATE_All_KEY_STR); 主要是为了生成文件的唯一名称(日期标记)
2015/09/01 13:42
回复
举报
String fileName = DateUtils.getNowTime(DateUtils.DATE_All_KEY_STR); 里面的DATE_All_KEY_STR报错,请问你import com.poweree.util.DateUtils; 引入的是啥jar包呢?
2015/07/02 22:48
回复
举报
com.poweree.util.DateUtils是哪个包啊?3
2014/08/20 09:32
回复
举报

引用来自“邓攀”的评论

苍老师亮了

13
2014/01/07 21:16
回复
举报
苍老师亮了
2014/01/07 18:11
回复
举报
更多评论
打赏
5 评论
16 收藏
0
分享
返回顶部
顶部