前台页面:

   
   
   
   
  1. <form id="addform" method="post" enctype="multipart/form-data" action="${base}/action/addPhoPic"> 
  2. <table border="0" class="perview" align="center"> 
  3.         <a href="#" onClick="toaddpic()">上传至相册a> 
  4.         <tr> 
  5.             <th>选择文件th> 
  6.             <th width="50%">预览图th> 
  7.         tr> 
  8.         <tr> 
  9.             <td height="200"><input id="idFile" name="upload" type="file" />td> 
  10.             <td align="center"><img id="idImg" />td> 
  11.         tr> 
  12. table> 
  13. form> 

Java后台处理:

   
   
   
   
  1. //与前台页面空间name一致
  2. private File upload;  
  3. //反射,得到文件类型,文件名称
  4.     private String uploadContentType;  
  5.     private String uploadFileName;  
  6.     public String doAddPhoPic(){
  7. //自己的PhotoService接口处理
  8.         IPhotoService photoService=BeanFactory.getBean(BeanConstants.WB_PHOTO_SERVICE);  
  9.         Photo photo=new Photo();
  10. //这里简单的demo没有要把名字规范,也没有对图片有剪切或缩小处理,所以就简单的把上传的图片以1,2,3命名 
  11.         int count=photoService.queryPhotoList().size();  
  12.         count++;  
  13.         String file_path1="";  
  14.         String file_path2="";  
  15.         try {
  16. //上传至该项目所在本地目录   
  17.             file_path1=Constants.BASE_ROOT+"/fullsize"+"/"+count+".jpg";  
  18.             file_path2=Constants.BASE_ROOT+"/thumbs"+"/"+count+".jpg";  
  19.             photo.setPicName(photoService.queryPhotoList().size()+1+".jpg");  
  20.             photo.setPicUrl(file_path2);  
  21.             photoService.insertPhoto(photo);  
  22.             System.out.println("---"+file_path1);  
  23.             System.out.println("---"+file_path2);  
  24. //对文件进行写操作
  25.             FileOutputStream fos1=new FileOutputStream(file_path1);  
  26.             FileOutputStream fos2=new FileOutputStream(file_path2);
  27. //对文件进行读操作 
  28.             FileInputStream fis=new FileInputStream(upload);  
  29.             byte[] buffer=new byte[1024];  
  30.             int len=0;  
  31. //读入流,保存至byte数组
  32.             while((len=fis.read(buffer))>0){  
  33.                 fos1.write(buffer,0,len);  
  34.                 fos2.write(buffer,0,len);  
  35.             }  
  36.             fos1.close();  
  37.             fos2.close();  
  38.             fis.close();  
  39.         } catch (Exception e) {  
  40.             e.printStackTrace();  
  41.         }  
  42.         list=photoService.queryPhotoList();  
  43.         return SUCCESS;  
  44.     }