JQuery插件之uploadify

uploadify是一款用於上傳文件的JQuery插件,使用它在選擇文件後有一個進度條用於顯示用戶選擇了什麼文件。

使用方法

1.引入資源文件

<script src="js/jquery-1.11.1.js" type="text/javascript"></script>
<script src="js/uploadify/jquery.uploadify-3.2.1.js" type="text/javascript"></script>
<link rel="stylesheet" type="text/css" href="js/uploadify/uploadify.css">
2.創建一些HTML元素便於使用uploadify(id爲queue的div的作用是  顯示用戶選擇的文件列表,並提供一個進度條,當用戶選擇上傳時即可根據進度條查看文件上傳的程度,值之所以要爲queue,是因爲在調用type=file的uploadify方法時傳入的"queueID"的值是"queue")

<div id="queue"></div>
<input id="file_upload" name="file_upload" type="file" multiple="true" />
<a href="javascript:$('#file_upload').uploadify('upload')">開始上傳</a> 
<a href="javascript:$('#file_upload').uploadify('cancel')">取消所有上傳</a>
3.寫一些JQuery代碼
$(function() {
            var timestamp = new Date().getTime();
            $('#file_upload').uploadify({
                'formData' : {
                    'timestamp' : timestamp,
                    'token' : 'unique_salt' + timestamp
                },// 設置想後臺傳遞的參數 如果設置該參數,那麼method應該設置爲get,才能得到參數
                'swf' : 'js/uploadify/uploadify.swf',// 指定swf文件
                'uploader' : 'url',// 後臺處理的頁面
                'cancelImg' : 'js/uploadify/uploadify-cancel.png',// 取消按鈕圖片路徑
                "queueID" : 'queue',// 上傳文件頁面中,你想要用來作爲文件隊列的元素的id, 默認爲false  自動生成,  不帶#
                'method' : 'get',// 設置上傳格式
                'auto' : false,// 當選中文件後是否自動提交
                'multi' : false,// 是否支持多個文件上傳
                'removeCompleted':false,
                'buttonText' : '選擇文件',// 按鈕顯示的文字 
                uploadLimit:1,
		fileObjName:'uploadfile',//這個文件對象的name爲uploadfile
                fileSizeLimit:1024 * 10,
                'onUploadSuccess': function (file, data, response) {// 上傳成功後執行
                   /* $('#' + file.id).find('.data').html(' 上傳完畢');*/
                   console.log(file);
                 }
            });
        });
4.上面一段JS代碼的作用是初始化uploadify的一些參數,當設置好了這些參數後,再調用uploadify的一些方法即可使用

5.下面提供一段java後臺代碼

// 獲得參數
        String timestamp = request.getParameter("timestamp");
        String token = request.getParameter("token");
        System.out.println(timestamp);
        System.out.println(token);
        // 獲得文件
        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) {
            System.out.println(ex.getMessage());
            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);

6.本人使用過程中遇到過的錯誤

  • 使用Chrome時,uploadify插件出現錯誤,錯誤原因是Chrome的Flash過期了或者Chrome版本過高
  • 小demo一直未能成功,不是代碼的問題,而是瀏覽器的問題,更換瀏覽器試試。
  • uploadify有許多屬性,方法,事件,請另行查閱資料。




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章