1. 程式人生 > >jquery file upload示例

jquery file upload示例

jquery file upload是一款實用的上傳檔案外掛,專案中剛好用到,在這裡記錄分享一下。

一:準備相關js檔案

jquery file upload 下載地址:點選開啟連結  點選下面紅圈中的按鈕下載


jquery.js下載地址:點選開啟連結

二:匯入js檔案

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

<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<!-- jquery file upload相關js -->
<script src="js/jquery.ui.widget.js"></script>
<script src="js/jquery.iframe-transport.js"></script>
<script src="js/jquery.fileupload.js"></script>
<script src="js/jquery.fileupload-process.js"></script>
<script src="js/jquery.fileupload-validate.js"></script>

三:jsp程式碼

<style>
/* input樣式 */
#uploadImg{
display: none;
}

/* button樣式 */
#chooseFile{
background: #93b6fc;
}

#uploadFile,#rechooseFile {
display: none;
background: #93b6fc;
}

#image{
  width:200px;
  height:200px;
}

/* 進度條樣式 */
.bar { 
 background-image: -webkit-linear-gradient(top,#5cb85c 0,#449d44 100%); 
 background-image: -o-linear-gradient(top,#5cb85c 0,#449d44 100%); 
 background-image: -webkit-gradient(linear,left top,left bottom,from(#5cb85c),to(#449d44)); 
 background-image: linear-gradient(to bottom,#5cb85c 0,#449d44 100%); 
 filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff5cb85c', endColorstr='#ff449d44', GradientType=0); 
 background-repeat: repeat-x; 
 height: 20px; 
 line-height: 20px; 
 -webkit-box-shadow: inset 0 -1px 0 rgba(0,0,0,.15); 
 box-shadow: inset 0 -1px 0 rgba(0,0,0,.15); 
 -webkit-transition: width .6s ease; 
 -o-transition: width .6s ease; 
 transition: width .6s ease; 
}
#progress { 
 filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffebebeb', endColorstr='#fff5f5f5', GradientType=0); 
 background-repeat: repeat-x; 
 height: 20px; 
 width: 0%; 
 margin-bottom: 20px; 
 overflow: hidden; 
 background-color: #f5f5f5; 
 border-radius: 4px; 
 -webkit-box-shadow: inset 0 1px 2px rgba(0,0,0,.1); 
 box-shadow: inset 0 1px 2px rgba(0,0,0,.1); 
 margin-top: 20px; 
}
</style>
<body>
	<div class="jquery-fileupload">
		<div class="">
			<input id="uploadImg" type="file" name="uploadImg" multiple style="display: none" /> 
				<button id="chooseFile">+選擇檔案</button> 
				<button id="uploadFile">~開始上傳</button>
				<button id="rechooseFile">+重新選擇</button>
		</div>
		<div>
			<img id="image" src="">
		</div>
		<div id="progress">
			<div class="bar" style="width: 0%;"></div>
		</div>
	</div>
</body>

四:js程式碼

$(function() {

		$("#chooseFile").on("click", function() {
			$("#uploadImg").click();
		});

		$('#uploadImg').fileupload({
			url : '/FileTest/upload',//請求傳送的目標地址
			Type : 'POST',//請求方式 ,可以選擇POST,PUT或者PATCH,預設POST
			//dataType : 'json',//伺服器返回的資料型別
			autoUpload : false,
			acceptFileTypes : /(gif|jpe?g|png)$/i,//驗證圖片格式
			maxNumberOfFiles : 1,//最大上傳檔案數目
			maxFileSize : 1000000, // 檔案上限1MB
			minFileSize : 100,//檔案下限  100b
			messages : {//檔案錯誤資訊
				acceptFileTypes : '檔案型別不匹配',
				maxFileSize : '檔案過大',
				minFileSize : '檔案過小'
			}
		})
		//圖片新增完成後觸發的事件
		.on("fileuploadadd", function(e, data) {
			//validate(data.files[0])這裡也可以手動來驗證檔案格式和大小
			
			//隱藏或顯示頁面元素
			$('#progress .bar').css( 
			    'width', '0%'
			  );
			$('#progress').hide();
			$("#chooseFile").hide();
			$("#uploadFile").show();
			$("#rechooseFile").show();
			
			//獲取圖片路徑並顯示
			var url = getUrl(data.files[0]);
			$("#image").attr("src", url);
			
			//繫結開始上傳事件
			$('#uploadFile').click(function() {
				$("#uploadFile").hide();
				jqXHR = data.submit();
				//解綁,防止重複執行
				$("#uploadFile").off("click"); 
			})
			
			//繫結點選重選事件
			$("#rechooseFile").click(function(){
				$("#uploadImg").click();
				//解綁,防止重複執行
				$("#rechooseFile").off("click"); 
			})
		})
		//當一個單獨的檔案處理佇列結束觸發(驗證檔案格式和大小)
		.on("fileuploadprocessalways", function(e, data) {
			//獲取檔案
			file = data.files[0];
			//獲取錯誤資訊
			if (file.error) {
				console.log(file.error);
				$("#uploadFile").hide();
			}
		})
		//顯示上傳進度條
		.on("fileuploadprogressall", function(e, data) {
			$('#progress').show();
			 var progress = parseInt(data.loaded / data.total * 100, 10); 
			  $('#progress').css( 
			   'width','15%'
			  ); 
			  $('#progress .bar').css( 
			   'width',progress + '%'
			  ); 
		})
		//上傳請求失敗時觸發的回撥函式
		.on("fileuploadfail", function(e, data) {
			console.log(data.errorThrown);
		})
		//上傳請求成功時觸發的回撥函式
		.on("fileuploaddone", function(e, data) {
			alert(data.result);
			
		})
		//上傳請求結束後,不管成功,錯誤或者中止都會被觸發
		.on("fileuploadalways", function(e, data) {

		})

		
		//手動驗證
		function validate(file) {
			//獲取檔名稱
			var fileName = file.name;
			//驗證圖片格式
			if (!/.(gif|jpg|jpeg|png|gif|jpg|png)$/.test(fileName)) {
				console.log("檔案格式不正確");
				return true;
			}
			//驗證excell表格式
			/*  if(!/.(xls|xlsx)$/.test(fileName)){
			 	alert("檔案格式不正確");
			 	return true;
			 } */

			//獲取檔案大小
			var fileSize = file.size;
			if (fileSize > 1024 * 1024) {
				alert("檔案不得大於一兆")
				return true;
			}
			return false;
		}

		//獲取圖片地址
		function getUrl(file) {
			var url = null;
			if (window.createObjectURL != undefined) {
				url = window.createObjectURL(file);
			} else if (window.URL != undefined) {
				url = window.URL.createObjectURL(file);
			} else if (window.webkitURL != undefined) {
				url = window.webkitURL.createObjectURL(file);
			}
			return url;
		}

	});


五:伺服器端程式碼

1:匯入依賴

<dependency>
	<groupId>commons-fileupload</groupId>
	<artifactId>commons-fileupload</artifactId>
	<version>1.3.1</version>
</dependency>

2:配置springmvc上傳解析器
<!-- springmvc檔案上傳解析器 -->
<bean id="multipartResolver"
	class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
	<property name="defaultEncoding" value="UTF-8" />
	<property name="maxUploadSize" value="-1" />
</bean>

3:java程式碼
package com.mote.upload;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

@Controller
public class FileUploadController {
	
	/**
	 * 將圖片上傳到伺服器根目錄下
	 * @param @param multipartFile
	 * @param @param request
	 * @param @return
	 * @return String
	 * @throws
	 */
	@RequestMapping(value = "/upload",method=RequestMethod.POST)
	@ResponseBody
	public String upload(
			@RequestParam("uploadImg") MultipartFile multipartFile,
			HttpServletRequest request) {
		try {
			//獲取專案路徑
			String realPath = request.getSession().getServletContext()
					.getRealPath("");
			InputStream inputStream = multipartFile.getInputStream();
			String contextPath = request.getContextPath();
			//伺服器根目錄的路徑
			String path = realPath.replace(contextPath.substring(1), "");
			//根目錄下新建資料夾upload,存放上傳圖片
			String uploadPath = path + "upload";
			//獲取檔名稱
			String filename = getUploadFileName(multipartFile);
			//將檔案上傳的伺服器根目錄下的upload資料夾
			File file = new File(uploadPath, filename);
			FileUtils.copyInputStreamToFile(inputStream, file);
			//返回圖片訪問路徑
			String url = request.getScheme() + "://" + request.getServerName()
					+ ":" + request.getServerPort() + "/upload/" + filename;
			return url;
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;

	}
	
	
	/**
	 * 獲取上傳檔案的名稱,新檔名為原檔名加上時間戳
	 *
	 * @param multipartFile
	 *            multipartFile
	 * @return 檔名
	 */
	private String getUploadFileName(MultipartFile multipartFile) {
		String uploadFileName = multipartFile.getOriginalFilename();
		String fileName = uploadFileName.substring(0,
				uploadFileName.lastIndexOf("."));
		String type = uploadFileName.substring(uploadFileName.lastIndexOf("."));
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
		String timeStr = sdf.format(new Date());
		String name = fileName + "_" + timeStr + type;
		return name;
	}

}