天天看点

web开发图片的上传code

 @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

 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);

  }

 }

继续阅读