java上传文件

本文介绍了一个用于文件上传的功能,并详细展示了如何实现图片的压缩及格式转换。文章中包括了完整的Java代码示例,涵盖了文件读取、写入以及利用第三方库进行图片处理的过程。
    public Boolean uploadFiles(File files, String filenames, String newfilenames,String url)
            throws IOException {
        String root = "";
        boolean t = true;
        root = ServletActionContext.getServletContext().getRealPath("/systemfile/picture");
        try{
            FileOutputStream fos = new FileOutputStream(root+"/"+newfilenames);
            FileInputStream fis = new FileInputStream(files);
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = fis.read(buffer)) > 0) {
                fos.write(buffer, 0, len);
            }
            fis.close();
            fos.close();
            /* 这儿填写你转化后的图片存放的文件夹 */
            ImageChange r = new ImageChange();
                String xx = newfilenames.substring(newfilenames.lastIndexOf("."), newfilenames.length());
                if(ImageUtil.isImage(new File(root +"/"+ newfilenames))){
                    if(xx.indexOf("gif")>-1||xx.indexOf("GIF")>-1){
                        FileOutputStream fos1 = new FileOutputStream(root+"1/"+newfilenames);
                        FileOutputStream fos2 = new FileOutputStream(root+"2/"+newfilenames);
                        FileInputStream fis1 = new FileInputStream(files);
                        FileInputStream fis2 = new FileInputStream(files);
                        int len1 = 0;int len2 = 0;
                        while ((len1 = fis1.read(buffer)) > 0 && (len2 = fis2.read(buffer)) > 0) {
                            fos1.write(buffer, 0, len1);
                            fos2.write(buffer, 0, len2);
                        }
                        fis1.close();
                        fis2.close();
                        fos1.close();
                        fos2.close();
                    } else {
                        int width = Integer.valueOf(MyProperties.getByKey("width"));
                        int width2 = Integer.valueOf(MyProperties.getByKey("width2"));
                        /* 这个参数是要转化成的宽度 */
                        BufferedImage f = r.getBufferedImage(root +"/"+ newfilenames);
                        url=root +"/"+ newfilenames;
                        r.writeHighQuality(r.zoomImage(f, width), root +"1/", newfilenames);
                        r.writeHighQuality(r.zoomImage(f, width2), root +"2/", newfilenames);
                        f.flush();
                    }
                }
        } catch (Exception ex) {
            System.out.println("error:"+ex);
            t = false;
        }
        return t;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值