plupload+artdialog實現多平台檔案上傳

來源:互聯網
上載者:User

標籤:style   class   blog   code   java   http   

背景:本來項目中使用的前端檔案上傳控制項是uploadify,一切相安無事了一段時間後。現場傳來”喜訊“,客戶要用ipad使用系統,還想上傳圖片。客戶老爺一拍腦門,研發就要加班加點。大家知道uploadify是依賴flash的,所以在ios,mac系統上都不行。於是,經過一番google,找到了plupload。上手比較簡單。

 

頁面html代碼:

head標籤中包含必要的js檔案

<script type="text/javascript" src="js/jquery-1.9.1.min.js" ></script><!-- art dialog --><script type="text/javascript" src="artdialog/artDialog.source.js?skin=blue"></script><!-- plupload --><script type="text/javascript" src="plupload/plupload.full.js"></script>

body標籤中的頁面元素

<!-- 觸發彈出框 --><a id="uploadBtn" class="optionbtn inline" href="#">檔案上傳</a><div id="uploadContent"  class="" style="display:none;height:300px;overflow-x:hidden;overflow-y:auto;">    <div id="choosefile">        <span>單個檔案支援小於100M</span><br/>        <a id="uploadify" href="javascript:void(0);">選擇檔案</a>    </div>     <div id="uploadfileQueue" style="border: 1px solid #a7c5e2;height: 228px;width: 350px;">            </div></div>
<pre id="console"></pre>
 

script標籤中的代碼

var globalUploader;function _plupload(){      var uploader = new plupload.Uploader({      runtimes : ‘html5,flash,silverlight,html4‘,      browse_button: ‘uploadify‘, //頁面上瀏覽檔案的DOM對象的id屬性       container: ‘uploadContent‘,//包含browse_button的div      url: ‘/uploadAction!localUpload.action‘,//接收檔案上傳的action      flash_swf_url : ‘/folder/js/plupload/Moxie.swf‘,      silverlight_xap_url : ‘/folder/js/plupload/Moxie.xap‘,      filters : {??            max_file_size : ‘100mb‘,//限制上傳檔案大小            mime_types: [//限制上傳檔案類型                     {title : "Image files", extensions : "jpg,gif,png"}                 ]      },      init: {            PostInit: function() {                $(‘#uploadfileQueue‘).html(‘‘);            },            UploadFile : function(up,file){//BeforeUpload後觸發                              },            BeforeUpload : function(up,file){//點擊按鈕後上傳前觸發,此處可以做查詢同名檔案,檢查剩餘空間等操作                //檢查是否有重名檔案,有則直接在檔案名稱末尾加個括弧和數字以示區分                      $.ajax({                    url:"/folder/personal/personalAction!getNewFileName.action",                    type:"POST",                    async:false,                    data:{‘upFileName‘ : file.name, ‘globalPid‘ : globalPid},                    dataType:"json",                    success:function(data){                        //上傳前設定參數                          up.setOption(‘multipart_params‘, {                          upFileName : data.newFileName,                           upFileType : file.name.split(".")[file.name.split(".").length - 1],//尾碼                             upFileSize : file.size,                          parentId : globalPid                        });                    },                    error:function(XMLHttpRequest, textStatus, errorThrown){                        messageAlert("對不起,檔案["+file.name+"]上傳準備失敗",‘‘);//                        $(‘#uploadify‘).uploadify(‘cancel‘,file.id);//按id取消某個上傳任務                    }                });                                },            ????????????????????????FileFiltered: function(up, file){                //選擇檔案後觸發            },            FilesAdded: function(up, files) {//檔案添加到隊列中                var i = 0;//記錄檔案清單編號,刪除用                plupload.each(files, function(file) {                    $(‘#uploadfileQueue‘).html($(‘#uploadfileQueue‘).html() +                             ‘<div id="‘ + file.id + ‘" class="uploadify-queue-item"><div class="cancel"><a href="javascript:_plupload_removeFile(‘+i+‘,‘+file.id+‘)"></a></div><span class="fileName">‘ + file.name +                             ‘ (‘ + plupload.formatSize(file.size) + ‘)</span><b></b><div class="uploadify-progress"><div class="uploadify-progress-bar"></div></div></div>‘);                    i ++;                });            },            UploadProgress: function(up, file) {//點擊開始上傳後觸發,此處可以添加進度條,利用file.percent                document.getElementById(file.id).getElementsByTagName(‘b‘)[0].innerHTML = ‘<span>-‘ + file.percent + "%</span>";//百分比                $(‘#‘ + file.id).find(‘.uploadify-progress-bar‘).css(‘width‘, file.percent + ‘%‘);//進度條            },            Error: function(up, err) {//出錯觸發                document.getElementById(‘console‘).innerHTML += "\n錯誤 #" + err.code + ": " + err.message;            },            FileUploaded: function(up, file, info) {//一個檔案上傳完觸發                            // Fires when a file is successfully uploaded.                data = eval( "(" + info.response + ")" );//伺服器返回的資料,此處可以修改頁面上的檔案清單等                                              },            UploadComplete: function(up, files){//所有檔案上傳完觸發                //Fires when all files in a queue are uploaded.            }        }    });    uploader.init();    globalUploader = uploader;}function popUpDialog(){    artDialog({        id: ‘file-upload‘,        title: ‘檔案上傳‘,        fixed: true,        lock: true,        content: $("#uploadContent")[0],        button:[{            name: ‘開始上傳‘,            focus:true,            callback: function(){                globalUploader.start();                return false;            }        },{            name: ‘關閉‘,            callback: function(){                $(‘#uploadfileQueue‘).html(‘‘);//刪掉上傳隊列的內容                globalUploader.files.splice(0,globalUploader.files.length);//清除上傳隊列中的內容                return true;            }        }],        close: function(){            $(‘#uploadfileQueue‘).html(‘‘);//刪掉上傳隊列的內容            globalUploader.files.splice(0,globalUploader.files.length);//清除上傳隊列中的內容        }    });}$(function(){    $(‘#uploadBtn‘).click(function(){        popUpDialog();    });    _plupload();});

後台代碼就不寫了,我用的struts2後台action中使用private File file接收的檔案,改其他名字就是null,目前還不知道怎麼設定控制項中的這個值

然後效果就是這個樣子

想要進度條需要加上這些css樣式,就是已有控制

<style type="text/css">    #uploadfileQueue {        position: relative;        left: 0;        top: 0;        border: 1px solid #a7c5e2;        margin-bottom: 5px;        height: 228px;        width: 350px;        overflow-x: hidden;        overflow-y: auto;    }    .uploadify-queue-item {    /* background-color: #F5F5F5; */        background-color: #FFF;        -webkit-border-radius: 3px;        -moz-border-radius: 3px;        border-radius: 3px;        font: 11px Verdana, Geneva, sans-serif;        /* margin-top: 5px; */        margin: 5px 5px 5px 5px;        max-width: 350px;        padding: 10px;    }    .uploadify-progress {        background-color: #E5E5E5;        margin-top: 10px;        width: 100%;    }    .uploadify-progress-bar {        background-color: #0099FF;        height: 3px;        width: 1px;    }</style>

最後的效果。什麼,還想要uploadify的刪除隊列裡檔案的叉叉,好吧

在style裡再加上這段

.uploadify-queue-item .cancel a {    background: url(‘js/uploadify-cancel.png‘) 0 0 no-repeat;    float: right;    height: 16px;    text-indent: -9999px;    width: 16px;}

當然還得加上刪除的js代碼。這裡官方api裡面有removeFile(file)但是,用再這裡不太好使。於是使用了另一個方法splice(num,length),num是從第幾個開始刪,length是刪除的個數。

function _plupload_removeFile(removeNum,fileId){    globalUploader.files.splice(removeNum,1);//刪除部分檔案    $(fileId).fadeOut();}

最終效果。

聯繫我們

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