jfinal 文件上传

/**
  *
  */
 public void upload() {
  String path = new SimpleDateFormat("yyyy/MM/dd").format(new Date());
  // 上传文件名称
  UploadFile file = getFile("imgFile", PathKit.getWebRootPath() + "/temp");
  File source = file.getFile();
  String fileName = file.getFileName();
  String extension = fileName.substring(fileName.lastIndexOf("."));
  String prefix;
  if (".png".equals(extension) || ".jpg".equals(extension)
    || ".gif".equals(extension)) {
   prefix = "img";
   fileName = generateWord() + extension;
  } else {
   prefix = "file";
  }
  JSONObject json = new JSONObject();
  try {
   FileInputStream fis = new FileInputStream(source);
   File targetDir = new File(PathKit.getWebRootPath() + "/" + prefix
     + "/u/" + path);
   if (!targetDir.exists()) {
    targetDir.mkdirs();
   }
   File target = new File(targetDir, fileName);
   if (!target.exists()) {
    target.createNewFile();
   }
   FileOutputStream fos = new FileOutputStream(target);
   byte[] bts = new byte[300];
   while (fis.read(bts, 0, 300) != -1) {
    fos.write(bts, 0, 300);
   }
   fos.close();
   fis.close();
   json.put("error", 0);
   json.put("url", "/" + prefix + "/u/" + path + "/" + fileName);
   source.delete();
  } catch (FileNotFoundException e) {
   json.put("error", 1);
   json.put("message", "上传出现错误,请稍后再上传");
  } catch (IOException e) {
   json.put("error", 1);
   json.put("message", "文件写入服务器出现错误,请稍后再上传");
  }
  renderJson(json.toJSONString());
 }

 private String generateWord() {
  String[] beforeShuffle = new String[] { "2", "3", "4", "5", "6", "7",
    "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J",
    "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V",
    "W", "X", "Y", "Z" };
  List<String> list = Arrays.asList(beforeShuffle);
  Collections.shuffle(list);
  StringBuilder sb = new StringBuilder();
  for (int i = 0; i < list.size(); i++) {
   sb.append(list.get(i));
  }
  String afterShuffle = sb.toString();
  String result = afterShuffle.substring(5, 9);
  return result;
 }

转载于:https://my.oschina.net/bluedreaming/blog/411771

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值