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

来源:互联网 发布:uc文书 知乎 编辑:程序博客网 时间:2024/06/05 11:50

转:https://my.oschina.net/crazyiter/blog/173480

导读: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>

四、截图:

 



 
0 0
原创粉丝点击