Flash上傳組件之SWFUpload檔案上傳

來源:互聯網
上載者:User

標籤:並且   vax   ++   max   緩衝   客戶   invalid   提示   ssid   

SWFUpload是一個用戶端檔案上傳工具,最初由Vinterwebb.se開發,它通過整合Flash與JavaScript技術為WEB開發人員提供了一個具有豐富功能繼而超越傳統<input type="file" />標籤的檔案上傳模式。

目前此項目放在:https://code.google.com/p/swfupload/

對應的中文API:http://leeon.me/upload/other/swfupload.html

由於SWFUpload是falsh和JavaScript結合開發的,這可能在HTML5流行的今天可能不太適合。而且SWFUpload和官網早就不更新了。推薦使用另一個外掛程式Plupload,這個外掛程式會自動檢測當前瀏覽器適合的上傳方式:HTML5、Flash、Silverlight。

SWFUpload的主要特點:

* 可以同時上傳多個檔案;

* 類似AJAX的無重新整理上傳;

* 可以顯示上傳進度;

* 良好的瀏覽器安全色性;

* 相容其他JavaScript庫 (例如:jQuery, Prototype等);

* 支援Flash 8和Flash 9;

SWFUpload不同於其他基於Flash構建的上傳工具,它有著優雅的代碼設計,開發人員可以利用XHTML、CSS和JavaScript來隨心所欲的定製它在瀏覽器下的外觀;它還提供了一組簡明的JavaScript事件,藉助它們開發人員可以方便的在檔案上傳過程中更新頁面內容來營造各種動態效果。

 

二、一般的開發流程

1、引入對應的JS和CSS檔案。

2、執行個體化SWFUpload對象,進行對象的初始化的配置。

3、瀏覽網頁,開啟並選取要上傳的檔案。

4、後台接收前台傳送的檔案流,進行處理。

5、後台返回對應的參數並進行前台提示。

這是我做的一個例子效果如下:

例一:

例二:

例一的代碼:

index.jsp

<%-- Created by IntelliJ IDEA. --%><%@ page contentType="text/html;charset=UTF-8" language="java" %><html><head>    <title>swfUpload上傳檔案(Java和Jquery)</title>    <script type="text/javascript" src="jquery/jquery-1.8.2.min.js"></script>    <script type="text/javascript" src="swfupload/swfupload.js"></script>    <link href="css/style.css" rel="stylesheet"></head><body><div id="swfPlaceHold"></div><ol id="fileList"></ol><input type="button" value="上傳" id="submit"></body><script type="text/javascript" src="swfupload/swfuploadHandlers.js"></script></html>

swfuploadHandlers.js

/** * Created by zhang on 14-2-25. */var queueErrorArray;var setting = {    upload_url: "/upload",       //幕後處理的程式路徑    flash_url: "swfupload/swfupload.swf", //swf程式路徑    file_types: "*.jpg;*.png;*.gif;*.mp4;*.wmv",     //允許上傳檔案種類    file_types_description: "Web Image", //對上傳檔案的描述    file_size_limit: "200MB",         //檔案上傳的大小單位預設為KB    file_upload_limit: 0,    //debug    debug: false,    //handlers    file_dialog_start_handler: fileDialogStar,   //開啟選擇對話方塊觸發的事件    file_queued_handler: fileQueued,             //把檔案加入上傳隊列觸發的事件    file_queue_error_handler: fileError,       //檔案排入佇列錯誤時觸發的事件    file_dialog_complete_handler: fileDialogComplete, //檔案選擇完成觸發的事件    upload_start_handler: uploadStar,               //檔案上傳觸發的事件    upload_progress_handler: uploadprogress,        //上傳中觸發的事件    upload_complete_handler: uploadComplete,        //上傳完成觸發的事件    upload_success_handler: uploadSuccess,         //上傳成功時觸發的事件    //button    button_placeholder_id: "swfPlaceHold",    button_text: "請選擇上傳檔案",    button_width: 270,    button_height: 20,    button_cursor: SWFUpload.CURSOR.HAND,    button_window_mode: SWFUpload.WINDOW_MODE.TRANSPARENT};var swfup = new SWFUpload(setting);/*********************************************handler************************************//** * 開啟檔案對話方塊時的觸發的事件 */function fileDialogStar() {    if (queueErrorArray) {        queueErrorArray = null;    }}/** * 檔案加入上傳隊列時觸發的事件 * @param 選擇上傳的檔案對象 */function fileQueued(file) {    var swfup = this;        //當前的swfupload執行個體對象    var listItem = "<li id=‘" + file.id + "‘>";    listItem += "檔案:<em>" + file.name + "</em>(" + Math.round(file.size / 1024) + "KB)<span id=‘progressValue‘></span>";    listItem += "<div id=‘progressBar‘><div id=‘progress‘></div></div>";    listItem += "<p id=‘statue‘></p><span id=‘cancle‘></span></li>";    $("#fileList").append(listItem);    //按鈕的取消事件    $("li#" + file.id + " #cancle").click(function (e) {        swfup.cancelUpload(file.id);        $("li#" + file.id).remove();    });}/** * 檔案排入佇列錯誤觸發的事件 * @param file上傳的檔案對象 * @param errorCode返回的錯誤碼 * @param msg 錯誤資訊 */function fileError(file, errorCode, msg) {    //錯誤隊列數組    if (!queueErrorArray) {        queueErrorArray = [];    }    errorFile = {        file: file,        code: errorCode,        error: ‘‘    };    switch (errorCode) {        case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT:            errorFile.error = ‘檔案大小超出限制‘;            break;        case SWFUpload.QUEUE_ERROR.INVALID_FILETYPE:            errorFile.error = ‘檔案類型不允許‘;            break;        case SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED:            errorFile.error = ‘超出檔案數量限制.‘;            break;        case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE:            errorFile.error = ‘你選擇的檔案是空的‘;            break;        case SWFUpload.UPLOAD_ERROR.HTTP_ERROR:            errorFile.error = ‘伺服器出錯‘;            break;        case SWFUpload.UPLOAD_ERROR.MISSING_UPLOAD_URL:            errorFile.error = ‘程式沒有設定upload_url屬性‘;            break;        case SWFUpload.UPLOAD_ERROR.IO_ERROR:            errorFile.error = ‘讀取或傳輸檔案時發生錯誤‘;            break;        case SWFUpload.UPLOAD_ERROR.ZERO_BYTE_FILE:            errorFile.error = ‘檔案為空白檔案‘;            break;        case SWFUpload.UPLOAD_ERROR.SECURITY_ERROR:            errorFile.error = ‘上傳受到了安全方面的限制‘;            break;        case SWFUpload.UPLOAD_ERROR.UPLOAD_FAILED:            errorFile.error = ‘上傳出現錯誤‘;            break;        default :            errorFile.error = ‘上傳檔案出錯,錯誤碼:‘ + errorCode;            break;    }    queueErrorArray.push(errorFile);}/** * 選擇檔案對話方塊關閉時觸發,報告所選檔案個數、加入上傳隊列檔案數及上傳隊列檔案總數 * @param numSelected 選擇的檔案數目 * @param numQueued 排入佇列的檔案數目 * @param numTotalInQueued 上傳檔案隊列中檔案總數 */function fileDialogComplete(numSelected, numQueued, numTotalInQueued) {    if (queueErrorArray && queueErrorArray.length) {    //如果有錯誤檔案        var table = $(‘<table><tr><td>檔案</td><td>大小</td></tr></table>‘);        for (var i in queueErrorArray) {            var tr = $(‘<tr></tr>‘);            var info = ‘<td>‘ + queueErrorArray[i].file.name + ‘<span style="color:red">(‘ + queueErrorArray[i].error + ‘)</span></td>‘                + ‘<td>‘ + queueErrorArray[i].file.size + ‘bytes</td>‘;            table.append(tr.append(info));        }        $(‘body‘).append(table);    } else {        this.startUpload();             //開始上傳    }}/** * 檔案上傳觸發的事件 * @param file一個檔案對象 */function uploadStar(file) {    if (file) {        $(‘#fileList li#‘ + file.id).find(‘p#statue‘).text("上傳中。。。。。");        $(‘#fileList li#‘ + file.id).find(‘p#progress‘).width("0%");    }}/** *檔案上傳過程Flash定時調用的方法用來返回當前上傳的進度 * @param file 上傳檔案對象 * @param byteCompleted 上傳的位元組 * @param byteTotal 總的位元組 */function uploadprogress(file, byteCompleted, byteTotal) {    var percentByte = Math.round((byteCompleted / byteTotal) * 100);    //當前進度    $(‘#fileList li#‘ + file.id).find(‘span#progressValue‘).text(percentByte + "%");    $(‘#fileList li#‘ + file.id).find(‘div#progress‘).css(‘width‘, percentByte + ‘%‘);}/** * 檔案上傳完畢並且伺服器返回200狀態代碼時觸發 * @param file 上傳的檔案 * @param serverData * @param response */function uploadSuccess(file, serverData, response) {    var $item = $("#fileList li#" + file.id);    $item.find(‘div#progress‘).css(‘width‘, ‘100%‘);    $item.find(‘span#progressValue‘).css(‘color‘, ‘blue‘).text(‘100%‘);    $item.find(‘p#statue‘).html(‘上傳完成!‘).css(‘color‘, ‘green‘);}/** * 在一個上傳周期結束後觸發(uploadError及uploadSuccess均觸發) * 在此可以開始下一個檔案上傳(通過上傳組件的uploadStart()方法) * @param file 上傳完成的檔案對象 */function uploadComplete(file) {    //判斷隊列中還有沒有檔案    if (this.getStats().files_queued > 0) {        this.startUpload();    } else {        this.cancelUpload(this.fileProgressID);        $("#fileList li").remove();    }}/********************************按鈕事件綁定*********************************************/$(‘#submit‘).click(function () {    swfup.startUpload();});

後台對應處理的Servlet

package com.zxd.tool;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;import javax.servlet.ServletConfig;import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import java.io.*;import java.util.List;import java.util.UUID;/** * Created by zhang on 14-2-25. */@WebServlet("/upload")public class Upload extends HttpServlet {    private File tempDir;   //臨時路徑    private File saveDir;   //儲存路徑    /**     * servlet初始化事件     *     * @param config     * @throws ServletException     */    public void init(ServletConfig config) throws ServletException {        String uploadPath = config.getServletContext().getRealPath("/");        StringBuffer sb = new StringBuffer(uploadPath);        saveDir = new File(sb.append("\\upload").toString());        tempDir = new File(sb.append("\\temp").toString());        if (!saveDir.exists()) {            saveDir.mkdir();        }        if (!tempDir.exists()) {            tempDir.mkdir();        }    }    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {        this.doPost(request, response);    }    public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {        DiskFileItemFactory factory = new DiskFileItemFactory();        factory.setSizeThreshold(1 * 1024 * 1024);      //設定緩衝區大小        factory.setRepository(tempDir);             //設定臨時儲存目錄        ServletFileUpload sfu = new ServletFileUpload(factory); //Servelt檔案上傳對象        sfu.setFileSizeMax(200 * 1024 * 1024);  //200M        sfu.setHeaderEncoding("utf-8");        List<FileItem> list = null;        try {            list = sfu.parseRequest(request);       //得到檔案        } catch (FileUploadException e) {            e.printStackTrace();        }        int size = list.size();        for (int i = 0; i < size; i++) {//迴圈儲存檔案            FileItem file = list.get(i);            if (file.isFormField()) {   //如果是表單欄位                String name = file.getFieldName();  // 獲得該欄位名稱                String value = file.getString("utf-8"); //獲得該欄位值            } else {                String extName = file.getName().substring(      //得到副檔名                        file.getName().lastIndexOf("."));                String fname = UUID.randomUUID()+extName;                try {                    file.write(new File(saveDir, fname));  // 寫入檔案                } catch (Exception e) {                    e.printStackTrace();                }            }        }    }

Flash上傳組件之SWFUpload檔案上傳

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.