1. 程式人生 > 其它 >SSM框架中jQuery-File-Upload的使用

SSM框架中jQuery-File-Upload的使用

技術標籤:jqueryjquery

jQuery File Upload 是一款實用的jQuery檔案上傳元件。

下載地址:https://github.com/blueimp/jQuery-File-Upload

1、下載完成後,將需要用到的資料夾複製到專案中

圖片007

2、在要使用上傳功能的jsp中引入js與css

注意:js檔案引入的先後順序不可以錯

本人實際開發的專案中全域性有引入bootstrap的樣式,在這裡不在程式碼中寫出了。

<link rel="stylesheet" href="js/jQueryFileUpload/css/jquery.fileupload.css"/>
<link rel="stylesheet" href="js/jQueryFileUpload/css/jquery.fileupload-ui.css"/>

<script type="text/javascript" src="js/jquery-1.11.1.min.js"></script>

<!-- jquery file upload相關js -->
<script type="text/javascript" src="js/jQueryFileUpload/js/vendor/jquery.ui.widget.js"></script>
<!--在IE下應載入此檔案解決跨域問題 -->
<script type="text/javascript" src="js/jQueryFileUpload/js/jquery.iframe-transport.js"></script>
<script type="text/javascript" src="js/jQueryFileUpload/js/jquery.fileupload.js"></script>
<script type="text/javascript" src="js/jQueryFileUpload/js/jquery.fileupload-process.js"></script>
<!--如果需要檔案型別驗證必須引入 -->
<script type="text/javascript" src="js/jQueryFileUpload/js/jquery.fileupload-validate.js"></script>

3、jsp程式碼

說明:實際開發的專案中,單個頁面樣式是在全域性的樣式下進行調整的,所以此處只是樣例而已,具體樣式調整要視自己的專案而定。

<style type="text/css">
    .upload_box {
        width: 500px;
        position: absolute;
        left: 216px;
    }
    .upload {
        width: 100px;
        font-size: 16px;
    }
    .progress_box {
        margin-top: 10px;
        display: none;
    }
</style>
<body>
    <div>
        <span><i class="fa fa-upload" aria-hidden="true"></i>附件上傳:</span>
        <span style="display: inline-block; margin-left: 1005px"></span>
    </div>

	<div class="upload_box">
        <!--將檔案域隱藏,設定label 的 for屬性的值為檔案域的id,然後再對label進行美化,這樣點選label也能開啟檔案選擇對話方塊 -->
        <label for="fileupload" class="upload btn btn-success glyphicon glyphicon-upload" style="line-height: 12px;">
            <span style="vertical-align: bottom; margin-left: -10px;">上傳</span>
        </label>

        <!-- 此處name="attach"與後臺接收的MultipartFile 後的名稱要統一 -->
		<input id="fileupload" type="file" name="attach" style="display: none;">
        
        <!--上傳進度條-->
		<div class="progress_box">
            <!--上傳進度使用 h5 中新增的 progress 元素,並建立一個id為upload_info 的控制元件,用於在上傳完成後顯示完成資訊-->
            <progress value="0" max="100" style="position: absolute; left: 200px; height: 25px; width: 200px;"></progress>
            <span id="upload_info" style="position: absolute; left: 410px;"></span>
        </div>
    </div>
</body>

上傳按鈕樣式:

圖片008

4、js程式碼

$(function () {
    InputFileUpload();
});

function InputFileUpload() {
	/*
	 * 這是實現上傳的核心程式碼 我們當前的要求如下 選擇檔案之後立即上傳 上傳過程中顯示進度條 上傳完成後顯示提示文字“上傳完成”
	 * 再次新增要上傳的檔案後,應該將提示文字“上傳成功”清除
	 */
    $('#fileupload').fileupload({
        url: apiUrl + '/Upload/upload.do',
        Type : 'POST',    //請求方式
        dataType: 'json', //伺服器返回的資料型別
        
        //autoUpload:是否自動上傳,即當檔案放入file之後便自動上傳,預設為true
        autoUpload: true,
        //acceptFileTypes: /(\.|\/)(xlsx|png|jp?g|gif)$/i, // 允許上傳的的檔案型別

//		maxNumberOfFiles: 1,//最大上傳檔案數目
        maxFileSize: 1024 * 1024 * 1024 * 2, // 最大上傳檔案大小
        minFileSize: 1, // 最小上傳檔案大小,單位B
        
		// <1>使用方法一:函式屬性
        // 全域性上傳處理事件的回撥函式,即上傳過程時觸發
        // 設定進度條:用data.loaded與data.total的比進行完成
        /*progressall: function (e, data) {
            var progress = parseInt(data.loaded / data.total * 100, 10);
            $('progress').val(progress);
            $('#upload_info').html(progress + '%');
        },
        //上傳完成之後的操作,顯示在img裡面
        done: function (e, data) {
            // 如果上傳的圖片,就取消下面程式碼的註釋
            //$("#uploadimg").attr('src', data.result.url);
        	
            $('#upload_info').html('上傳完成');
        },*/
    })
    // <2>使用方法二:繫結事件監聽函式,用.on()來用呼叫回撥函式
    //顯示上傳進度條:用data.loaded與data.total的比進行完成
	.on('fileuploadprogressall', function(e, data) {
		var progress = parseInt(data.loaded / data.total * 100, 10);
        $('progress').val(progress);
        $('#upload_info').html(progress + '%');
	})
    // 圖片新增完成後觸發的事件:使用者再次選擇檔案後,清除提示文字,並設定進度條可見
    .on('fileuploadadd', function(e, data) {
    	var mark = validate(data.files[0]); // 手動來驗證檔案大小
    	if (mark) {
    		$('.progress_box').css('display', 'block');
            $('#upload_info').html('');
		}
    })
    /*
     * fileuploadadd 事件會在使用者新增上傳檔案後觸發
     * 所以在這個事件中,我們將預設隱藏的進度條控制元件顯示,並清除上次上傳成功後的提示文字。 然後解釋 done 事件
     * 此事件會在伺服器成功返回訊息時觸發,所以在這個事件中,我們顯示圖片預覽以及顯示成功後的提示文字
     */
    // 上傳請求成功時觸發的回撥函式
    .on('fileuploaddone', function (e, data) {
        $('#upload_info').html('上傳完成');
        
        var iconClass = "", attExt = "", html = "";
        var res = data.result.data;
        if (res.attExt != "") {
            attExt = res.attExt.substring(1).toLowerCase();
        }

        if ($.inArray(attExt, imageFormatArray) != "-1") {
            iconClass = "sfw-img";
        } else if ($.inArray(attExt,
            documentFormatArray) != "-1") {
            iconClass = "sfw-txt";
        } else if ($.inArray(attExt, videoFormatArray) != "-1") {
            iconClass = "sfw-video";
        } else {
            iconClass = "sfw-txt";
        }
        
        html = html+ 
        	 "<tr class='item' id='" + res.attachId + "'>" +
        		"<td class='type'><i class='icon sfw-icon "+ iconClass+ "'></i></td>" +
        		"<td class='title'><span class='td-content'>" + beautySub(res.attFilename) + "</span></td>" +
        		"<td class='datetime' style='border-collapse:collapse;border-left:60px solid white'>" +
        			"<span class='td-content'>" + new Date(res.uploadTime).format('yyyy-MM-dd ')+ "</span>" +
        		"</td>" +
        		"<td class='file-type' style='border-collapse:collapse;border-left:60px solid white'>" +
        			"<span class='td-content' name='attExt'>" + attExt + "</span>" +
        		"</td>" + 
        		"<td class='file-size' style='border-collapse:collapse;border-left:60px solid white'>" +
        			"<span class='td-content'>" + bytesToSize(res.attSize) + "</span>" +
        		"</td>" +
        		"<td class='opt' style='border-collapse:collapse;border-left:60px solid white'>" +
        			"<a href='javascript:void(0);'><i class='icon sfw-icon sfw-del' onclick=delAttachment1(\"" + res.attachId+ "\")></i></a>" +
        		"</td>" +
        	"</tr>";
        $("#attachment_list").append(html);
        
        enclosureAttachmentIds.push(res.attachId);
        attachmentCount++;
        console.log("上傳附件後enclosureAttachmentIds:" + enclosureAttachmentIds);
        
        $("#attachmentCount").text("已上傳附件" + attachmentCount + "個");
        $("#AttachmentArea").removeClass("hidden");
        $("#AttachmentArea").show();
    })
    //上傳請求結束後,不管成功,錯誤或者中止都會被觸發
	.on("fileuploadalways", function(e, data) {
		$('.progress_box').css('display', 'none');
	});
}

// 校驗檔案大小
function validate(file) {
    //獲取檔名稱
	var fileName = file.name;

	//驗證圖片格式
	/*if (!/.(gif|jpg|jpeg|png|gif|jpg|png)$/.test(fileName)) {
        alert("上傳檔案格式不正確!");
		return false;
	}

	//驗證excell表格式
	if(!/.(xls|xlsx)$/.test(fileName)){
		alert("上傳檔案格式不正確");
		return false;
	}*/

	// 獲取檔案大小
	var fileSize = file.size;
	if (fileSize > 1024 * 1024 * 1024 * 2) {
		alert("上傳檔案大小不能大於2G!");
		return false;
		
	} else if (fileSize == 0) {
		alert("上傳檔案大小不能為0!");
		return false;
	}
	
	return true;
}

說明:js程式碼,一些配置項羅列出來了,但是有的沒有用到,比如說檔案大小限制,這個是手動去校驗的。因為本人也是現學現用,具體的Options還沒有完全看懂。

最後附上上傳過程的圖片:

圖片009
圖處10

圖片11

圖片12