JQuery Uploadify 基於JSP的無重新整理上傳執行個體

來源:互聯網
上載者:User

 轉載自

http://www.cnblogs.com/cjt-java/archive/2012/09/01/2666696.html

項目需要實現一個無重新整理批量檔案上傳功能,仔細研究了下,發現JQuery 提供的Uploadify外掛程式十分不錯,不過官方的執行個體是基於php的,下面我用jsp+servlet簡單實現了這個功能,廢話少說,先看:

1、初始化頁面:

2、選擇多個檔案(可一次多選)後:

 

3、點擊開始上傳(上傳完就自動消失)

效果就是上面那樣,頁面不重新整理。下面上代碼:

1、首先先到官網下載最新的zip壓縮包http://www.uploadify.com

2、項目結構:

3、關鍵代碼:

index.jsp

<%@ page language="java" contentType="text/html; charset=utf-8"%>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://"
            + request.getServerName() + ":" + request.getServerPort()
            + path + "/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>Upload</title>

<!--裝載檔案-->
<link href="css/default.css" rel="stylesheet" type="text/css" />
<link href="css/uploadify.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="scripts/jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="scripts/swfobject.js"></script>
<script type="text/javascript" src="scripts/jquery.uploadify.v2.1.4.min.js"></script>

<!--ready事件-->
<script type="text/javascript">
    $(document).ready(function() {
        $("#uploadify").uploadify({
            'uploader' : 'scripts/uploadify.swf',
            'script' : 'servlet/Upload',//幕後處理的請求
            'cancelImg' : 'images/cancel.png',
            'folder' : 'uploads',//您想將檔案儲存到的路徑
            'queueID' : 'fileQueue',//與下面的id對應
            'queueSizeLimit' : 5,
            'fileDesc' : 'rar檔案或zip檔案',
            'fileExt' : '*.rar;*.zip', //控制可上傳檔案的副檔名,啟用本項時需同時聲明fileDesc
            'auto' : false,
            'multi' : true,
            'simUploadLimit' : 2,
            'buttonText' : 'BROWSE'
        });
    });
</script>
</head>

<body>
    <div id="fileQueue"></div>
    <input type="file" name="uploadify" id="uploadify" />
    <p>
        <a href="javascript:jQuery('#uploadify').uploadifyUpload()">開始上傳</a>&nbsp;
        <a href="javascript:jQuery('#uploadify').uploadifyClearQueue()">取消所有上傳</a>
    </p>
</body>
</html>

 web.xml

<?xml version="1.0" encoding="UTF-8"?>

<web-app version="2.4"

    xmlns="http://java.sun.com/xml/ns/j2ee"

    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee

    http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"> 

  <servlet>

    <servlet-name>upload</servlet-name>

    <servlet-class>com.xzit.upload.Upload</servlet-class>

  </servlet>

  <servlet-mapping>

    <servlet-name>upload</servlet-name>

    <url-pattern>/servlet/Upload</url-pattern>

  </servlet-mapping>

  <welcome-file-list>

    <welcome-file>index.jsp</welcome-file>

  </welcome-file-list>

</web-app>

 upload.java

package com.xzit.upload;

import java.io.File;

import java.io.IOException;

import java.util.Iterator;

import java.util.List;

import java.util.UUID;

 

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

 

import org.apache.commons.fileupload.FileItem;

import org.apache.commons.fileupload.FileUploadException;

import org.apache.commons.fileupload.disk.DiskFileItemFactory;

import org.apache.commons.fileupload.servlet.ServletFileUpload;

 

@SuppressWarnings("serial")

public class Upload extends HttpServlet {

    @SuppressWarnings("unchecked")

    public void doPost(HttpServletRequest request, HttpServletResponse response)

            throws ServletException, IOException {

        String savePath = this.getServletConfig().getServletContext()

                .getRealPath("");

        savePath = savePath + "/uploads/";

        File f1 = new File(savePath);

        System.out.println(savePath);

        if (!f1.exists()) {

            f1.mkdirs();

        }

        DiskFileItemFactory fac = new DiskFileItemFactory();

        ServletFileUpload upload = new ServletFileUpload(fac);

        upload.setHeaderEncoding("utf-8");

        List fileList = null;

        try {

            fileList = upload.parseRequest(request);

        } catch (FileUploadException ex) {

            return;

        }

        Iterator<FileItem> it = fileList.iterator();

        String name = "";

        String extName = "";

        while (it.hasNext()) {

            FileItem item = it.next();

            if (!item.isFormField()) {

                name = item.getName();

                long size = item.getSize();

                String type = item.getContentType();

                System.out.println(size + " " + type);

                if (name == null || name.trim().equals("")) {

                    continue;

                }

                //副檔名格式: 

                if (name.lastIndexOf(".") >= 0) {

                    extName = name.substring(name.lastIndexOf("."));

                }

                File file = null;

                do {

                    //組建檔案名:

                    name = UUID.randomUUID().toString();

                    file = new File(savePath + name + extName);

                } while (file.exists());

                File saveFile = new File(savePath + name + extName);

                try {

                    item.write(saveFile);

                } catch (Exception e) {

                    e.printStackTrace();

                }

            }

        }

        response.getWriter().print(name + extName);

    }

}

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.