java实现文件上传下载和图片压缩代码示例

分享一个在项目中用的到文件上传下载和对图片的压缩,直接从项目中扒出来的:)

代码如下:

package com.eabax.plugin.yundada.utils;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import net.coobird.thumbnailator.Thumbnails;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.eabax.plugin.yundada.GaContext;
public class FileUploadDownloadUtil {
    private static final Logger log = LoggerFactory.getLogger(FileUploadDownloadUtil.class);
    /**
     * 上传文件到服务器
     * @param request
     * @param type
     * @return
     * @throws Exception
     */
    public static String upload(HttpServletRequest request, String type) throws Exception {
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        String saveFileName = null;
        if (isMultipart) {
            String savePath = request.getSession().getServletContext()
                    .getRealPath("/")
                    + "/upload/";
            String tempPath = request.getSession().getServletContext()
                    .getRealPath("/")
                    + "/upload/temp/";
            File saveFile = new File(savePath);
            File tempFile = new File(tempPath);
            if (!saveFile.isDirectory())
                saveFile.mkdirs();
            if (!tempFile.isDirectory())
                tempFile.mkdirs();
            DiskFileItemFactory factory = new DiskFileItemFactory();
            factory.setSizeThreshold(1024 * 4);
            factory.setRepository(tempFile);
            ServletFileUpload uploader = new ServletFileUpload(factory);
            uploader.setSizeMax(20 * 1024 * 1024);
            List<FileItem> fileItems = uploader.parseRequest(request);
            for (FileItem item : fileItems) {
                if (item.isFormField()) {
                    // funName=item.getString();
                } else {
                    // String fileName=item.getName();
                    // String
                    // fix=fileName.substring(fileName.lastIndexOf(".")+1);
                    String fix = type;
                    Date nowDate = new Date();
                    SimpleDateFormat sdf = new SimpleDateFormat(
                            "yyyyMMddhhmmss");
                    String fileName = sdf.format(nowDate);
                    fileName += System.currentTimeMillis();
                    fileName += "." + fix;
                    saveFileName = "/upload/" + fileName;
                    File file = new File(savePath + fileName);
                    item.write(file);
                }
            }
        }
        return saveFileName;
    }
    /**
     * 上传头像
     * @param request
     * @param type
     * @return
     * @throws Exception
     */
    public static String uploadHeadShow(HttpServletRequest request,GaContext context, String type) throws Exception {
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        String saveFileName = null;
        String imagePath = "/upload/headshow/";
        String x = request.getParameter("length");
        String y = request.getParameter("wide");
        if (isMultipart) {
            String headShowServicePath = request.getSession().getServletContext()
                    .getRealPath("/")
                    + imagePath;
            Date nowDate = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat(
                    "yyyyMMddhhmmss");
            String fileName = context.getUsername()+sdf.format(nowDate);
            File headShowFile = new File(headShowServicePath);
            if (!headShowFile.isDirectory())
                headShowFile.mkdirs();
            DiskFileItemFactory factory = new DiskFileItemFactory();
            factory.setSizeThreshold(1024 * 4);
            factory.setRepository(headShowFile);
            ServletFileUpload uploader = new ServletFileUpload(factory);
            uploader.setSizeMax(20 * 1024 * 1024);
            List<FileItem> fileItems = uploader.parseRequest(request);
            for (FileItem item : fileItems) {
                if (item.isFormField()) {
                    // funName=item.getString();
                } else {
                    String fix = type;
                    fileName += "." + fix;
                    saveFileName = imagePath + fileName;
                    File file = new File(headShowServicePath + fileName);
                    item.write(file);
                }
            }
            //压缩图片
            if(x!=null&&!"".equals(x) && y!=null&&!"".equals(y)) {
                saveFileName = thumbnailatorImage(imagePath, fileName, type, Integer.parseInt(x), Integer.parseInt(y));
            }
        }
        return saveFileName;
    }
    /**
     * 上传分享图片
     * @param request
     * @param type
     * @return
     * @throws Exception
     */
    public static JSONObject uploadArticleImage(HttpServletRequest request,GaContext context, String type) throws Exception {
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        JSONObject saveFileName = new JSONObject();
        String imagePath = "";
        String x = request.getParameter("length");
        String y = request.getParameter("wide");
        if("4".equals(type)) {
            //分享上传图片路径
            imagePath = "/upload/articleimage/";
        }else if("5".equals(type)) {
            //链接上传图片路径
            imagePath = "/upload/linkimage/";
        } else {
            //头像上传图片路径
            imagePath = "/upload/headshow/";
        }
        if (isMultipart) {
            String headShowServicePath = request.getSession().getServletContext()
                    .getRealPath("/")
                    + imagePath;
            File headShowFile = new File(headShowServicePath);
            if (!headShowFile.isDirectory())
                headShowFile.mkdirs();
            DiskFileItemFactory factory = new DiskFileItemFactory();
            factory.setSizeThreshold(1024 * 4);
            factory.setRepository(headShowFile);
            ServletFileUpload uploader = new ServletFileUpload(factory);
            uploader.setSizeMax(20 * 1024 * 1024);
            List<FileItem> fileItems = uploader.parseRequest(request);
            for (FileItem item : fileItems) {
                UUID uuid = UUID.randomUUID();
                String fileName = uuid.toString();
                if (item.isFormField()) {
                    // funName=item.getString();
                } else {
                    String fix = type;
                    fileName += "." + fix;
                    saveFileName.put( uuid.toString(),imagePath + fileName);
                    File file = new File(headShowServicePath + fileName);
                    item.write(file);
                }
                //压缩图片
                if(x!=null&&!"".equals(x) && y!=null&&!"".equals(y)) {
                    String thumbnailatorName = thumbnailatorImage(imagePath, fileName, type, Integer.parseInt(x), Integer.parseInt(y));
                    saveFileName.put("thumbnailatorImage", thumbnailatorName);
                }
            }
        }
        return saveFileName;
    }
    /**
     * 上传压缩压缩并保存图片
     * @param oldSavePath 原文件路径
     * @param oldFileName 原文件名称
     * @param fix 文件类型
     * @param x 需要压缩的宽度
     * @param y 需要压缩的长度
     * @return
     * @throws IOException
     */
    public static String thumbnailatorImage(String oldSavePath,String oldFileName,String fix,int x,int y) throws IOException {
         //Thumbnail读取并压缩图片
        BufferedImage waterMarkBufferedImage = Thumbnails.of(oldSavePath+oldFileName) 
                //Thumbnail的方法,压缩图片
                .size(x, y)
                //读取成BufferedImage对象 
                .asBufferedImage(); 
        //把内存中的图片写入到指定的文件中 
        String savePath = oldSavePath+x+"-"+y+"/";
        File saveFile = new File(savePath);
        if (!saveFile.isDirectory())
            saveFile.mkdirs();
        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setSizeThreshold(1024 * 4);
        factory.setRepository(saveFile);
        ServletFileUpload uploader = new ServletFileUpload(factory);
        uploader.setSizeMax(20 * 1024 * 1024);
        UUID uuid = UUID.randomUUID();
        String fileName = uuid.toString();
        fileName += "." + fix;
        String saveFileName = savePath+fileName;
        File fileOutPut = new File(saveFileName); 
        ImageIO.write(waterMarkBufferedImage, fix, fileOutPut);
        return saveFileName;
    }
    /**
     * 下载压缩压缩并保存图片
     * @param oldSavePath 原文件路径
     * @param oldFileName 原文件名称
     * @param fix 文件类型
     * @param x 需要压缩的宽度
     * @param y 需要压缩的长度
     * @return
     * @throws IOException
     */
    public static String downloadThumbnailatorImage(String servicePath,String uri,int x,int y) throws IOException {
        //校验图片是否存在
        String uriSubPath = uri.substring(0, uri.lastIndexOf("/")+1);//文件名以前,服务器以后
        String fileName = uri.substring(uri.lastIndexOf("/")+1,uri.length());//文件名
        String getThumbnailatorPath = servicePath + uriSubPath+x+"-"+y+"/";
        String saveFileName = getThumbnailatorPath+fileName;
        File downFilePath = new File(getThumbnailatorPath);//压缩以后的文件夹
        File downFile = new File(saveFileName);//压缩以后的文件
        if (downFilePath.isDirectory()&&downFile.exists()) {
            return saveFileName;
        } else {
         //Thumbnail读取并压缩图片
            log.error(servicePath+uri);
            BufferedImage waterMarkBufferedImage = Thumbnails.of(servicePath+uri) 
                    //Thumbnail的方法,压缩图片
                    .size(x, y)
                    //读取成BufferedImage对象 
                    .asBufferedImage();
            if (!downFilePath.isDirectory()) {
                downFilePath.mkdirs();
            }
            DiskFileItemFactory factory = new DiskFileItemFactory();
            factory.setSizeThreshold(1024 * 4);
            factory.setRepository(downFilePath);
            ServletFileUpload uploader = new ServletFileUpload(factory);
            uploader.setSizeMax(20 * 1024 * 1024);
            File fileOutPut = new File(saveFileName); 
            ImageIO.write(waterMarkBufferedImage, "jpg", fileOutPut);
        }
        return saveFileName;
    }
}

以上就是本文分享的所有内容了,希望对大家能有所帮助。

(0)

相关推荐

  • Java图片裁剪和生成缩略图的实例方法

    一.缩略图 在浏览相册的时候,可能需要生成相应的缩略图. 直接上代码: public class ImageUtil { private Logger log = LoggerFactory.getLogger(getClass()); private static String DEFAULT_PREVFIX = "thumb_"; private static Boolean DEFAULT_FORCE = false;//建议该值为false /** * <p>Tit

  • java实现的图片裁剪功能示例

    本文实例讲述了java实现的图片裁剪功能.分享给大家供大家参考,具体如下: PicCut.java: package Tsets; import java.awt.Rectangle; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.Iterator; import javax

  • JavaWeb实现裁剪图片上传完整代码

    本文实例为大家分享了JavaWeb实现裁剪图片上传完整案例,供大家参考,具体内容如下 实现思路 •使用jcrop插件手机要裁剪图片的坐标  •将收集到的参数传递到后台,在后台使用java图形对象绘制图像进行裁剪 ◦后台处理流程: 1.将上传的图片按按照比例进行压缩后上传到文件服务器,并且将压缩后的图片保存在本地临时目录中. 2.将压缩后的图片回显到页面,使用jcrop进行裁剪,手机裁剪坐标(x,y,width,height) ■@paramx 目标切片起点坐标X ■@param y 目标切片起点

  • Java如何实现图片裁剪预览功能

    在项目中,我们需要做些类似头像上传,图片裁剪的功能,ok看下面文章! 需要插件:jQuery Jcrop 后端代码: package org.csg.upload; import java.awt.Rectangle; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.Itera

  • 详解Java中使用ImageIO类对图片进行压缩的方法

    最近做项目需要图片压缩处理,网上找的方法大都使用了 com.sun.image.codec.jpeg.* 这个包中的JPEGImageEncoder类,引入这个包后一直报错,各种google百度,尝试了各种方法,包括手动引jre中的rt.jar,以及在eclipse中把受访问限制的API提示从ERROR改为WARNING,等等,然而这些都是不好使的,因为后来我发现我的java-7-openjdk-amd64中的rt.jar里边根本就没有com.sun.image.*,貌似这个类在java7中已经

  • jquery.Jcrop结合JAVA后台实现图片裁剪上传实例

    本文介绍了头像裁剪上传功能,用到的技术有  jQuery,springmvc,裁剪插件用的是jcrop(中间遇到很多坑,最终跨越). 图片上传步骤: 1.用户选择图片 2.将图片传入后台:用户选择图片的时候选择的是各种各样的,但是我们的网页显示图片大小是有限的,所以我们就要在用户选择图片之后将图片添加到后台进行压缩,压缩成我们想要的大小,之后再显示到页面才好 3.利用jcrop裁剪工具对图片进行裁剪并且实时预览 4.点击确定按钮将裁剪用到的参数传入后台,后台图片进行剪切,之后缩放成我们需要的格式

  • 使用Java代码在Android中实现图片裁剪功能

    前言 Android应用中经常会遇到上传相册图片的需求,这里记录一下如何进行相册图片的选取和裁剪. 相册选取图片 1. 激活相册或是文件管理器,来获取相片,代码如下: private static final int TAKE_PICTURE_FROM_ALBUM = 1; private void takePictureFromAlbum() { Intent intent = new Intent(Intent.ACTION_GET_CONTENT); intent.setType("ima

  • Java实现图片上传到服务器并把上传的图片读取出来

    在很多的网站都可以实现上传头像,可以选择自己喜欢的图片做头像,从本地上传,下次登录时可以直接显示出已经上传的头像,那么这个是如何实现的呢? 下面说一下我的实现过程(只是个人实现思路,实际网站怎么实现的不太清楚) 实现的思路: 工具:MySQL,eclipse 首先,在MySQL中创建了两个表,一个t_user表,用来存放用户名,密码等个人信息, 一个t_touxiang表,用来存放上传的图片在服务器中的存放路径,以及图片名字和用户ID, T_touxiang表中的用户ID对应了t_user中的i

  • java裁剪图片并保存的示例分享

    我们将通过以下步骤来学习: 输入图像,指定要处理的图像路径允许用户拖放要剪裁的部分选择后使用 Robot 类来确定剪裁部分的坐标剪裁所选图像并保持接下来我们开始编码部分. Listing1: 引入的类 复制代码 代码如下: import java.awt.Graphics;  import java.awt.Rectangle;  import java.awt.Robot;  import java.awt.event.MouseEvent;  import java.awt.event.Mo

  • Java实现图片与Base64编码互转

    淘宝里面的html用base64转换图片,不知道为什么,不过看起来好像很美好,话不多说,直接上代码: import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import sun.misc.BASE64Decoder; import sun.misc.BA

随机推荐