功能設計源碼以及思路-圖片上傳篇

功能說明:圖片的上傳和查看圖片
具體實現:
    思路:首先讀取圖片的屬性,然後以流的形式建立在項目的指定路徑(類型:char[]),然後給圖片一個id和改項目指定的路徑,然後圖片的名稱我就是用的當前的時間,精確到秒(這確實也可以加上id或者一些附加值方面後期的一些查詢,我比較懶剛做就搞的最簡單的),數據庫中存的是圖片的id和url,頁面就是用的url顯示的。另外要說的是這裏沒有寫連接數據庫這塊,因爲是公司內部框架所以不能公佈。(大家可以用hibernate,或者jdbc都行)

首先是頁面:
當然我們這裏還是先讀取文件的屬性的,我是寫在後臺,然後在頁面導入的,後臺代碼如下:
/**
 * 讀取properties文件
 * @author Administrator
 *
 */
public class ConfigVersoin {
 private static Properties properties = null;
 /**
  * 讀取文件屬性
  * @param read
  */
 public static synchronized void readConfigProperties(boolean read) {
  if(properties != null && !read)
   return;
  InputStream input = null;
  try {
   input = ConfigVersoin.class.getClassLoader().getResourceAsStream("config.properties");
   if(read)
    properties = null;
   properties = new Properties();
   properties.load(input);
  } catch (IOException e) {
   e.printStackTrace();
  } finally {
   if(input != null)
    try {
     input.close();
    } catch (IOException e) {
     e.printStackTrace();
    }
  }
 }
 /**
  * 根據key讀取值
  * @param key
  * @return
  */
 public static String getProperties(String key) {
  if(properties == null){
   readConfigProperties(false);
  }
  return (String)properties.get(key);
 }
 
 
 /**
  * 根據類型讀取照片配置路徑
  * @param type 0頭像,1背景,2患者照片,4醫院照片,5應用照片
  * @return
  */
 public static String photoPath(String type){
  String path = ConfigVersoin.getProperties("photo_path");
  StringBuffer bf = new StringBuffer();
  bf.append(path).append("/");
  if("0".equals(type)){//頭像
   path = ConfigVersoin.getProperties("user_portrait");
   bf.append(path);
  }else if("1".equals(type)){//背景
   path = ConfigVersoin.getProperties("user_background");
   bf.append(path);
  }else if("2".equals(type)){//患者照片
   path = ConfigVersoin.getProperties("patient_portrait");
   bf.append(path);
  }else if("3".equals(type)){//醫院照片
   path = ConfigVersoin.getProperties("hospital_logo");
   bf.append(path);
  }else if("4".equals(type)){//應用照片
   path = ConfigVersoin.getProperties("app_img");
   bf.append(path);
  }
  bf.append("/");
  return bf.toString();
 }
 
 /**
  * 獲取版本號
  * @return
  */
 public static String jsversion(){
  return getProperties("js_versoin");
 }
 
}


HTML:
<%@page import="com.yuanqitech.web.util.ConfigVersoin"%>
 <div align="right" class="fudong"> 照片:<img src="${patientInfo.photo_url }"
       class="img_upload" type="2" comp="PatientInfoData" imgId="<s:property value="dialyse_id"/>" /></div>





後臺代碼:
/**
 * 圖片上傳
 * @author Administrator
 *
 */
public class ImgUnloadAction extends BaseFormAction {
 private ImgInfo img;
 
 public String init(){
  this.resultContent="/bqnjsp/img_upload.jsp";
  return resultName;
 }
 
 public String unload(){
  String poweremr = ServletActionContext.getRequest().getSession().getServletContext().getRealPath("/");
  String path = ConfigVersoin.photoPath(img.getType());
 
  FileUpload upload = new FileUpload();
 
  img = upload.upload(img, poweremr, path);
 
  int t = saveImgMsg(img.getImgId(), img.getImgPath(),img.getImgByte(), img.getComp());
 
  String msg ="{\"rc\":\""+t+"\",\"path\":\""+img.getImgPath().replace("\\", "/")+"\"}";
  HttpServletResponse response = ServletActionContext.getResponse();
  HttpParserUtil.flush(msg, response);
  return null;
 }
 
 private int saveImgMsg(String imgId,String path,byte[] bts,String comp){
  if(comp != null && !"".equals(comp)){
   CompService com = BaseDAOFactory.getCompService();
   com.addParameter(imgId);
   com.addParameterObject(bts);
   com.addParameter(path);
   Object o = com.invoke(comp, "uploadImg");
   if("1".equals(o.toString())){
    HttpSession session = ServletActionContext.getRequest().getSession();
    UserInfo user = (UserInfo) session.getAttribute("userInfo");
    user.setImage_url(path);//此處有修改
    session.setAttribute("userInfo", user);
   }
   return Integer.valueOf(o.toString());
  }else{
   return -1;
  }
 }
 public ImgInfo getImg() {
  return img;
 }
 public void setImg(ImgInfo img) {
  this.img = img;
 }
 
}



//設計到切圖片
public class FileUpload {
 
 public String uploadByte(byte[] b,String pathname,String imgtype){
  File dir = new File(pathname);
  if(!dir.exists())
      dir.mkdir();
  String rtp = DateUtil.dateToString(new Date(),"yyyyMMddHHmmss");
  String fileName = rtp + "." +imgtype;
 
  File saveFile = new File(dir,fileName);
 
  FileOutputStream fos = null;
  try {
      fos = new FileOutputStream(saveFile);//建立一個上傳文件的輸出流
   fos.write(b);//將strutsFile文件流寫入目標路徑中
  } catch (FileNotFoundException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }finally{
   try {
    fos.close(); //任何時候都關閉
   } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
  }
  return rtp;
 }
 
 public ImgInfo upload(ImgInfo imgInfo,String webpath,String filePath){
  System.out.println("filePath=="+filePath);
  if(imgInfo == null)
   return null;
  String imgfile = imgInfo.getFile();
 
 
  String path = webpath + filePath;
 
  try {
   Map<String,String> fileMap = getfile(imgfile);
   String file = fileMap.get("file");
   String imgtype = fileMap.get("type");
   
   byte[] b = new BASE64Decoder().decodeBuffer(file);
   
   //物理地址存入圖片,返回圖片ID
   String filename = new FileUpload().uploadByte(b, path,imgtype);
   //數據庫存放路徑
   String imgpath = filePath + filename +"."+ imgtype;
   imgInfo.setImgPath(imgpath);//存放圖片路徑
   imgInfo.setImgByte(b);//存放二進制圖片
   
   if(imgInfo.getX() != null && !"".equals(imgInfo.getX())){//剪切
    int ix = math(imgInfo.getX(),imgInfo.getWb());
    int iy = math(imgInfo.getY(),imgInfo.getHb());
    int iw = math(imgInfo.getW(),imgInfo.getWb());
    int ih = math(imgInfo.getH(),imgInfo.getHb());
   
    //物理路徑
    String t = path + filename +"."+ imgtype;
   
    ImageCut cut = ImageCut.init();
    cut.setImageCut(t,ix, iy, iw, ih);
    cut.cut();
   }
  } catch (Exception e) {
   e.printStackTrace();
  }
 
  return imgInfo;
 }
 
 /**
  * 根據64位圖片格式,解析圖片類型和數據
  * @param file
  * @return
  */
 private Map<String, String> getfile(String file){
  Map retMap = new HashMap();
  String[] files = file.split(",");
  String imgtype = files[0];
  int s = imgtype.indexOf(":")+1;
  int e = imgtype.indexOf(";");
  imgtype = imgtype.substring(s, e);
  String type = imgtype.split("/")[0];
  if("image".equals(type)){
   imgtype = imgtype.split("/")[1];
  }else{
   imgtype = "jpg";
  }
  retMap.put("type",imgtype);
  retMap.put("file", files[1]);
  return retMap;
 }
 
 /**
  * 乘法
  * @param w
  * @param b
  * @return
  */
 private int math(String w,String b){
  BigDecimal bx = new BigDecimal(w);
  BigDecimal by = new BigDecimal(b);
  BigDecimal bs = new BigDecimal("1");
  int j = bx.multiply(by).divide(bs,0,BigDecimal.ROUND_HALF_UP).intValue();
  return j;
 }
}





發佈了29 篇原創文章 · 獲贊 4 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章