1. 程式人生 > >Jfinal框架下結合ajaxFileupload實現多檔案上傳

Jfinal框架下結合ajaxFileupload實現多檔案上傳

距離寫程式碼時間有點長了,沒有及時總結,現在忘得差不多了。不過大概思路還在,也是有點參考價值的!

思路:

由於jfinal框架自身的問題,在實現多檔案上傳時很難獲取所有檔案的名字,只能獲取到一個input標籤裡面的名字而已,重寫框架是最佳的方法,但是對於初學者而言十分艱難,所以我這裡介紹另一種解決思路吧!

思路:

1、前端介面一個input標籤,使用ajaxFileupload.js實現對檔案的上傳。

2、後臺接收所有檔案,儲存到一個獨一無二的資料夾中

3、遍歷該資料夾裡面的所有檔案,獲取他們的名字,存入資料庫!

具體程式碼如下:

前端介面:

<!-- 上傳 -->
<input type="file" name="uploadfile" id="uploadfile" multiple="multiple">
監測點id:<input type="text" id="monPointId"><br>
描述:<input type="text" id="description"><br>
拍攝地點:<input type="text" id="location"><br>
<button id="upload" type="button" onclick="return false;">上傳</button>
<!-- 上傳js檔案,放到最後載入 -->
<script type="text/javascript" src="${contextPath}/resources/js/jquery-1.11.1.js"></script>
<script type="text/javascript" src="${contextPath}/resources/js/ajaxfileupload.js"></script>
<script type="text/javascript" src="${contextPath}/resources/js/upload.js"></script>

js:
$(document).ready(function() {
	$('#upload').click(function() {
		upload();   
	});
});
function upload() {
	var monPointId=$("#monPointId").val();
	var description=$("#description").val();
	var location=$("#location").val();
	$.ajaxFileUpload({
		url : '/upload?monPointId='+monPointId+'&description='+description+'&location='+location,   //提交的路徑
		type: 'post',
		secureuri : false, // 是否啟用安全提交,預設為false
		fileElementId : 'uploadfile', // file控制元件id
		dataType : 'json',
		data:{
			'monPointId' : monPointId,
			'description' : monPointId,
			'location' : monPointId,
		},
		success : function(data, status) {
			console.log("aa");
			console.log(data);
			console.log(status);
		},
		error : function(data, status) {
			alert("上傳失敗");
		}
	});
}

後臺:
	/**
	 * 多視訊檔案上傳
	 */
	@SuppressWarnings("unchecked")
	public void upload(){
		String dirName=CommonUtils.getCurrentTime();
		String contextPath = PathKit.getWebRootPath();
		String path = "/upload/video/" +dirName;
		String pathUrl = contextPath + path;
		Map<String,Object> map=new LinkedHashMap<String, Object>();
		try {
			List<UploadFile> uploadFile = getFiles("video/"+dirName);//在磁碟上儲存檔案
			System.out.println(uploadFile.size());
			String monPointId=getPara("monPointId");
			String description=new String(getPara("description").getBytes("iso-8859-1"),"utf-8");//亂碼控制
			String location=new String(getPara("location").getBytes("iso-8859-1"),"utf-8");
			SensorService service=new SensorService();
			map=(Map<String, Object>) service.uploadVideo(uploadFile, dirName, path,pathUrl, monPointId, description, location);
		} catch (Exception e) {
			e.printStackTrace();
			map.put("status", false);
			map.put("msg", "伺服器異常!");
			ExcelImportUtil.deleteDir(new File(pathUrl));
		}
		System.out.println(map);
		renderJson(map);
	}


demo下載