Java調用uploadify實現文件上傳Demo實現

導讀:uploadify是來自國外的一款優秀的基於jQuery的文件上傳插件,主要功能是批量上傳文件,此插件在項目中已被普遍之用,因而決定花點時間搞了一個基於Java語言的demo,特此公佈出來。 javascript

1、採用版本及頁面基本引入介紹css

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

咱們須要在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> java

2、uploadify頁面初始化jquery

一、在頁面須要展現的上傳的地方加入以下代碼:
  <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'文件盒上傳進度的顯示。 web

二、初始化上傳組件:
$(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 + "上傳失敗");
            }
        });
}); apache

3、uploadify上傳處理的Java代碼json

一、上傳servlet代碼: app

這裏咱們使用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; this

/**
 * 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); 主要是爲了生成文件的惟一名稱(日期標記)

二、在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>

4、截圖:

 




 

uploadify的下載和詳細介紹,詳見:http://www.mbaike.net/techs/1938.html

相關文章
相關標籤/搜索