1. 程式人生 > >文章標題 使用ajaxFileupload+struts2完成檔案的上傳以及回顯到jsp的連結地址

文章標題 使用ajaxFileupload+struts2完成檔案的上傳以及回顯到jsp的連結地址

積累點滴,從這一刻開始
jsp頁面部分
第一步: jsp頁面匯入 ajaxfileupload.js檔案
第二步:編寫上傳檔案的文字框:
這裡寫圖片描述
第三步:這裡寫圖片描述
struts2後臺部分
第一步:private File file;
private String fileFileName;
private String fileFileContentType; //struts2處理上傳的三個基本屬性
第二步:
public void uploadFile(){
try {
//判斷檔案型別
Pattern reg=Pattern.compile(“[.]jpg|png|jpeg|gif$”);
Matcher matcher=reg.matcher(fileFileName);
if(!matcher.find()){
message=”{\”msg\”:\”檔案格式不正確\”,\”status\”:\”error\”}”; //返回的json資料中必須要有status:error這個鍵值對,就會去執行error的回撥函式
outJson(message);
return ;
}
//設定檔案的儲存路徑
File file = new File(DBTools.PATH); // 判斷資料夾是否存在,如果不存在則建立資料夾
if (!file.exists()) {
file.mkdir();
}
//設定檔案的唯一名稱
File f = this.getFile();
FileInputStream inputStream = new FileInputStream(f);
String []fileUn=fileFileName.split(“\.”);
fileFileName=user.getUserId()+”.”+fileUn[1];
FileOutputStream outputStream = new FileOutputStream(DBTools.PATH + “\”
+ fileFileName);
//讀取圖片以及寫入圖片
IOUtils.copy(inputStream, outputStream);//IOUtils工具類【把輸入流物件中的資料複製到輸出流物件中】
inputStream.close();
outputStream.flush();
outputStream.close();
message=”{\”msg\”:\”上傳成功\”,\”status\”:\”success\”}”;//message可以設定 src=“圖片的連結地址,用作jsp頁面的顯示;返回的json資料中必須要有 status:success, 就會執行success的回撥函式
outJson(message);
} catch (Exception e) {
e.printStackTrace();
message=”{\”msg\”:\”上傳失敗\”,\”status\”:\”error\”}”;
outJson(message);
}finally{
Conn.close(conn);
}

    }

重點內容
1:檔案上傳儲存的是伺服器的一個資料夾,也可以使用配置檔案來設定儲存檔案的路徑;或者使用資料庫中一個欄位來儲存儲存的路徑
2:如果使用者在前臺頁面中需要檢視圖片,需要利用action類中的response中的輸出流物件輸出檔案/圖片,然後jsp中設定