項目中圖片處理總結
1、將圖片保存到項目中的image文件夾底下(這是最初的設計,當時考慮這樣頁面獲取圖片比較簡單)
2、將圖片保存的物理磁盤上,相對於項目路徑(將第一種方案改爲第二種方案的原因是考慮到包替換的時候會把原來的圖片替換掉。版本升級和包替換都不方便)
3、將圖片保存到物理磁盤、固定盤符、固定文件夾底下(將第二總方案改爲第三中方案的原因是考慮到雙機,必須把圖片保存到共享磁盤上)
4、將圖片保存到數據庫(沒使用這總方法,原因是這總方法的佔用數據庫的空間,讀取的時候也有性能問題)
5、將圖片保存到圖片服務器(可惜本項目沒有圖片服務器)
下面保存圖片
//先保存圖片到服務器
if (imageBean.getImageFile() != null && imageBean.getImageFile().length() > 0)
{
//得到圖片名稱
String imageName = imageBean.getImageFileFileName();
File file = imageBean.getImageFile();
//獲取圖片後綴
String ext = imageName.substring(imageName.lastIndexOf('.') + 1).toLowerCase(Locale.CHINA);
//重新生成文件名
String filename = UUID.randomUUID().toString() + "." + ext;//構建文件名稱
//構建文件保存的目錄 這是方案一的實現
//String pathdir = "/images/room/prototype";
//得到圖片保存目錄的真實路徑 這是方案二的實現
//String realpathdir = new File(suiteImagePath).getCanonicalFile().getPath();
//String realpathdir = ServletActionContext.getServletContext().getRealPath(pathdir);
//FileTools.saveFile(file, realpathdir, filename);
//這個方法是保存文件到對應的路徑
FileTools.saveFile(file, suiteImagePath, filename);
imageBean.setName(filename);
imageBean.setPullpath(suiteImagePath + "/" + filename);
}
//保存圖片到數據庫
int id = imageDAO.addImage(imageBean);
imageBean.setId(id);
return imageBean;
接下來看下頁面如何獲取圖片
<img src="../showImage.action?imagePath=${imageBean.pullpath}" />
InputStream file = null;
OutputStream toClient = null;
try
{
//imagePath = new File(imagePath).getCanonicalFile().getPath();
file = new FileInputStream(new File(imagePath));
//int i = file.available(); // 得到文件大小
byte data[] = new byte[KeyConstant.DEFAULT_BYTE_SIZE];
int endFlag = 0;
ServletActionContext.getResponse().setContentType("image/*"); // 設置返回的文件類型
toClient = ServletActionContext.getResponse().getOutputStream(); // 得到向客戶端輸出二進制數據的對象
while (endFlag != -1)
{
endFlag = file.read(data);
if (endFlag == -1)
{
break;
}
toClient.write(data, 0, endFlag); // 輸出數據
}
toClient.flush();
toClient.close();
}
...後面是處理異常和關閉流