需要用到的包和資源
js文件:
jquery.min.js(需要jQuery的支持)
ajaxfileupload.js(處理異步上傳的文件)
外部包:
jfinal-2.0-bin-with-src.jar(JFinal核心包)
fastjson-1.2.7-sources.jar和fastjson-1.2.7.jar(用於json數據的處理)
cos-26Dec2008.jar(支持JFinal自帶的上傳功能)
源代碼說明
上傳的JSP頁面代碼
<!-- 上傳圖片 -->
<input type="file" name="image" id="imageFile">
<button id="upload" onclick="return false;">上傳</button>
<!-- 存儲圖片地址,並顯示圖片 -->
<input type="hidden" name="pictureSrc" id="pictureSrc">
<div id="show"></div>
<!-- 圖片上傳js文件,放到最後加載 -->
<script type="text/javascript" src="${contextPath}/js/jquery.min.js"></script>
<script type="text/javascript" src="${contextPath}/js/ajaxfileupload.js"></script>
<script type="text/javascript" src="${contextPath}/js/upload.js"></script>
在頁面上導入jquery.min.js和ajaxfileupload.js兩個文件,upload.js文件是用來來提交數據和上傳文件,並接收服務器回發的json數據
upload.js源代碼
$(document).ready(function() {
$('#upload').click(function() {
upload($('#imageFile').val()); //函數參數爲上傳的文件的本機地址
});
});
function upload(fileName) {
$.ajaxFileUpload({
url : 'upload/imageUpload', //提交的路徑
secureuri : false, // 是否啓用安全提交,默認爲false
fileElementId : 'imageFile', // file控件id
dataType : 'json',
data : {
fileName : fileName //傳遞參數,用於解析出文件名
}, // 鍵:值,傳遞文件名
success : function(data, status) {
if (data.error == 0) {
var src = data.src;
$('#show').append("<img src='" + src + "'>"); //顯示圖片
// 存儲已上傳圖片地址
var oldSrc = $('#pictureSrc').val();
var newSrc = "";
if (oldSrc != "")
newSrc = oldSrc + ";" + src;
else
newSrc = src;
$('#pictureSrc').val(newSrc); //保存路徑
} else {
alert(data.message);
}
},
error : function(data, status) {
alert(data.message);
}
});
}
一次上傳一張圖片,可多次上傳。上傳成功後,將圖片顯示在頁面上,並將圖片地址存放在type=”hidden”的input標籤中,並按”;”來分隔圖片地址
用於處理的controller文件UploadController.java文件代碼
public void imageUpload() {
UploadFile uploadFile = getFile("imgFile", PathKit.getWebRootPath()
+ "/temp", 20 * 1024 * 1024, "utf-8"); // 最大上傳20M的圖片
// 異步上傳時,無法通過uploadFile.getFileName()獲取文件名
String fileName = getPara("fileName");
fileName = fileName.substring(fileName.lastIndexOf("\\") + 1); // 去掉路徑
// 異步上傳時,無法通過File source = uploadFile.getFile();獲取文件
File source = new File(PathKit.getWebRootPath() + "/temp/" + fileName); // 獲取臨時文件對象
String extension = fileName.substring(fileName.lastIndexOf("."));
String savePath = PathKit.getWebRootPath() + "/upload/images/"
+ CommonUtils.getCurrentDate();
JSONObject json = new JSONObject();
if (".png".equals(extension) || ".jpg".equals(extension)
|| ".gif".equals(extension) || "jpeg".equals(extension)
|| "bmp".equals(extension)) {
fileName = CommonUtils.getCurrentTime() + extension;
try {
FileInputStream fis = new FileInputStream(source);
File targetDir = new File(savePath);
if (!targetDir.exists()) {
targetDir.mkdirs();
}
File target = new File(targetDir, fileName);
if (!target.exists()) {
target.createNewFile();
}
FileOutputStream fos = new FileOutputStream(target);
byte[] bts = new byte[1024 * 20];
while (fis.read(bts, 0, 1024 * 20) != -1) {
fos.write(bts, 0, 1024 * 20);
}
fos.close();
fis.close();
json.put("error", 0);
json.put("src", "upload/images/" + CommonUtils.getCurrentDate()
+ "/" + fileName); // 相對地址,顯示圖片用
source.delete();
} catch (FileNotFoundException e) {
json.put("error", 1);
json.put("message", "上傳出現錯誤,請稍後再上傳");
} catch (IOException e) {
json.put("error", 1);
json.put("message", "文件寫入服務器出現錯誤,請稍後再上傳");
}
} else {
source.delete();
json.put("error", 1);
json.put("message", "只允許上傳png,jpg,jpeg,gif,bmp類型的圖片文件");
}
renderJson(json.toJSONString());
}
先通過JFinal自帶的文件上傳類UploadFile,將文件上傳到項目根目錄下面的temp文件夾下面,臨時保存起來。
又因爲異步上傳時,無法通過uploadFile.getFile();直接獲取文件進而對文件進行後續操作,故先通過獲取臨時文件文件名,進而獲取該臨時文件對象,再對該文件進行操作,如下代碼
String fileName = getPara("fileName");
fileName = fileName.substring(fileName.lastIndexOf("\\") + 1); // 去掉路徑
// 異步上傳時,無法通過File source = uploadFile.getFile();獲取文件
File source = new File(PathKit.getWebRootPath() + "/temp/" + fileName); // 獲取臨時文件對象
後面將文件名和後綴名分隔開,判斷是否爲圖片文件:若不是,則刪除臨時文件,拒絕上傳並返回報錯的json數據;若是,則複製上傳的臨時文件,並重命名放入指定文件夾下,刪除上傳的臨時文件。其中,CommonUtils爲工具類,主要獲取當前日期和時間,代碼如下
package org.dny.utils;
import java.text.SimpleDateFormat;
import java.util.Date;
public class CommonUtils {
/** 默認的格式化方式 */
private static final String defaultFormat = "yyyy-MM-dd HH:mm:ss";
public static String getDate() {
SimpleDateFormat dateFormat = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss");
Date currentDate = new Date();
String formatCurrentDate = dateFormat.format(currentDate).toString();
return formatCurrentDate;
}
public static String getCurrentDate() {
String format = "yyyy-MM-dd";
Date date = new Date();
date.setTime(System.currentTimeMillis());
if (format == null || "".equals(format.trim())) {
format = defaultFormat;
}
SimpleDateFormat sdf = new SimpleDateFormat(format);
return sdf.format(date);
}
public static String getCurrentTime() {
String format = "yyyyMMddHHmmss";
Date date = new Date();
date.setTime(System.currentTimeMillis());
if (format == null || "".equals(format.trim())) {
format = defaultFormat;
}
SimpleDateFormat sdf = new SimpleDateFormat(format);
return sdf.format(date);
}
}
運行結果
項目包下載
項目包下載地址:
http://download.csdn.net/detail/u013539342/9422743
下載後導入MyEclipse 2014可直接運行
參考地址
感謝前輩們的付出,我只是個搬運工+擴展者
參考地址:
http://www.cnblogs.com/kissdodog/archive/2012/12/15/2819025.html
http://www.oschina.net/code/snippet_2255303_43121