基于Struts2的文件上传

1.页面的form表单需要添加文件上传的标示:  enctype="multipart/form-data"

基本原理:先读入,再写出

        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        String imagePath;
        long systemTime = System.currentTimeMillis();
        picFileName = StringUtil.nullToString(systemTime)+picFileName;
        
        try {
            bis = new BufferedInputStream(new FileInputStream(pic));
            BufferedInputStream imageBis = new BufferedInputStream(new FileInputStream(pic));
            BufferedImage bi  = ImageIO.read(imageBis);  
            int imageWidth = bi.getWidth();
            int imageHeight = bi.getHeight();
            if(imageWidth!=650 || imageHeight!=250 ){
                resultMap.put("message", "需上传650*250尺寸的图片,请重新选择图片");
                resultMap.put("success", "false");
                return SUCCESS;
            }
            ServletContext application = ServletActionContext.getServletContext();
            Map<String, Object> params = ActionContext.getContext().getParameters();
            imagePath =params.get("savePath")+"/"+picFileName;
            bos = new BufferedOutputStream(new FileOutputStream(application.getRealPath(savePath) + "/" + picFileName));
            byte[] buf = new byte[1024];
            int r = 0;
            while((r = bis.read(buf)) != -1){
                bos.write(buf,0,r);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            resultMap.put("message", "图片路径出错,请联系系统管理员!");
            resultMap.put("error", true);
            resultMap.put("success","false");
            return SUCCESS;
        } catch (IOException e) {
            e.printStackTrace();
            resultMap.put("message", "上传过程中出现问题,请重试!");
            resultMap.put("error", true);
            resultMap.put("success","false");
            return SUCCESS;
        }finally{
            try {
                if(bis != null){
                    bis.close();
                }
                if(bos != null){
                    bos.close();
                }
            } catch (IOException e){
                e.printStackTrace();
            }
        }
      
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值