web开发图片的上传code

来源:互联网 发布:四图连拍的是什么软件 编辑:程序博客网 时间:2024/05/16 05:12

 

/**
  * @param baseInfo BaseInfo
  * 修改信息,上传图片
  */
 @Override
 public void editBaseInfo(BaseInfo baseInfo) {
  String employeeNo = baseInfo.getEmployeeNo();
  String picPath = baseInfo.getPicPath();
  if (StringUtils.isNotEmpty(picPath)) {
   DesEncrypt desEncrypt;
   String p;
   try {
    desEncrypt = new DesEncrypt();
    p = desEncrypt.decrypt(picPath);
   } catch (Exception e) {
    throw new RuntimeException();
   }
   String path = ConfigFactory.getString("picPath") + "temp";
   File dir = new File(path);
   if (!dir.exists()) {
    dir.mkdirs();
   }
   String fileName = employeeNo + "." + TransferCommFunc.getFileExt(p);
   String filePath = path + File.separator + fileName;
   TransferCommFunc.moveFile(new File(p), filePath);
   baseInfo.setPhotoId(fileName);
  }
  baseInfoDao.editBaseInfo(baseInfo);
  
 }

 

 

TransferCommFunc.java

 /**
  * 移动文件位置
  * @param file 文件
  * @param toDir 文件目标位置
  * @throws IOException
  */
 public static void moveFile(File file ,String toDir) {
  InputStream in = null;
  OutputStream out = null;
  try {
   File f = new File(toDir);
   if (!f.exists()) {
    f.createNewFile();
   }
   in = new FileInputStream(file);
   out = new FileOutputStream(f);
   int i;
   byte[] buf = new byte[1024];
   while ((i = in.read(buf)) != -1) {    
    out.write(buf, 0, i);
   }
   out.flush();
  } catch (FileNotFoundException e) {
   LOG.error(e);
  } catch (IOException e) {
   LOG.error(e);
  } finally {
   IOUtils.closeQuietly(in);
   IOUtils.closeQuietly(out);
  }
 }