文件上传

来源:互联网 发布:汉王软件 编辑:程序博客网 时间:2024/06/01 09:29
public void imgUpload(){
    //jFinal上传至临时文件夹
    UploadFile uploadFile = getFile("file", PathKit.getWebRootPath() + "/temp", 20 * 1024 * 1024, "utf-8"); // 最大上传20M的图片
    // 异步上传时,无法通过uploadFile.getFileName()获取文件名
    String fileName = uploadFile.getFileName();
    fileName = fileName.substring(fileName.lastIndexOf("\\") + 1); //去掉路径,获取文件名


    // 异步上传时,无法通过File source = uploadFile.getFile();获取文件
    File source = new File(PathKit.getWebRootPath() + "/temp/" + fileName); // 获取临时文件对象


    String extension = fileName.substring(fileName.lastIndexOf("."));
   
    String id = getPara("orderinfoid");
    BhInsorderNew insorderNew = BhService.me().getOrdernewById(id);//今年订单信息
    BhCarinfo carinfo = BhService.me().getCarInfo(insorderNew.getStr("license_no"), insorderNew.getStr("inquiry_no"));//车辆信息
   
    String licenseNo = carinfo.getStr("license_no");//车牌号
    if(licenseNo != null && licenseNo.equalsIgnoreCase("")){
    licenseNo = licenseNo.substring(1);
    }
   
    String uploadname = getPara("uploadname");//页面传来的参数,确定上传的是第几张照片
   
    String savePath = PathKit.getWebRootPath() + "/upload/" + DateUtil.getTodayStr();//获得保存的路径
    savePath += "/" + licenseNo;//根据车牌号创建文件夹
   
    JSONObject json = new JSONObject();


    if (".png".equals(extension) || ".jpg".equals(extension) || ".gif".equals(extension) || "jpeg".equals(extension) || ".bmp".equals(extension))
    {
       fileName = DateUtil.getTodaySecNum() + "_" + uploadname + extension;
       
       try
       {
    FileInputStream fis = new FileInputStream(source);//读入流


    File targetDir = new File(savePath);
    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[1024 * 20];
    while (fis.read(bts, 0, 1024 * 20) != -1)
    {
       fos.write(bts, 0, 1024 * 20);
    }


    fos.close();
    fis.close();
    json.put("status", 1);
    json.put("msg", "上传成功");
    source.delete();
   
    String idPhoto = insorderNew.getStr("id_photo");//保存照片信息到数据库
    if(idPhoto == null || idPhoto.equalsIgnoreCase("")){
    insorderNew.set("id_photo", DateUtil.getTodayStr() + "/" + licenseNo + "/" + fileName);
    }else{
    insorderNew.set("id_photo", idPhoto + ";" + DateUtil.getTodayStr() + "/" + licenseNo + "/" + fileName);
    }
    insorderNew.update();
       } catch (FileNotFoundException e)
       {
    json.put("status", 0);
    json.put("msg", e.getMessage());
       } catch (IOException e)
       {
    json.put("status", 0);
    json.put("msg", e.getMessage());
       }
    }else
    {
       //source.delete();
       json.put("status", 0);
       json.put("msg", "只允许上传png,jpg,jpeg,gif,bmp类型的图片文件");
    }
    renderJson(json.toJSONString());    
    }
原创粉丝点击