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

 更新时间:2015年03月12日 14:43:28   投稿:hebedich  
本文给大家介绍的是项目中经常需要用到的一个常用的功能,使用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;
    }
}

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

相关文章

  • SpringBoot+Netty实现简单聊天室的示例代码

    SpringBoot+Netty实现简单聊天室的示例代码

    这篇文章主要介绍了如何利用SpringBoot Netty实现简单聊天室,文中的示例代码讲解详细,对我们学习SpringBoot有一定帮助,感兴趣的同学可以了解一下
    2022-02-02
  • Java栈的运用之中缀表达式求值详解

    Java栈的运用之中缀表达式求值详解

    本文来介绍一题中缀表达式求值的问题,就是给定一个中缀计算式,编写程序将这个式子运算结果给计算出来,其实和后缀表达式的思路差不多,都是栈的运用问题,感兴趣的可以了解一下
    2022-11-11
  • JAVA如何获取jvm和操作系统相关信息

    JAVA如何获取jvm和操作系统相关信息

    这篇文章主要介绍了JAVA获取jvm和操作系统相关信息,使用Java自带的类进行获取系统运行的相关信息,在这整理记录分享一下,需要的朋友可以参考下
    2022-10-10
  • java异常处理的简单练习

    java异常处理的简单练习

    下面小编就为大家带来一篇java异常处理的简单练习。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2016-06-06
  • java显示声音波形图示例

    java显示声音波形图示例

    这篇文章主要介绍了java显示声音波形图示例,需要的朋友可以参考下
    2014-05-05
  • 值得Java开发者关注的7款新工具

    值得Java开发者关注的7款新工具

    作为老牌语言Java,其生态圈也出来了一些有关云服务、监控、文档分享方面的工具,这篇文章主要介绍了Java开发者值得关注的7款新工具,感兴趣的小伙伴们可以参考一下
    2016-07-07
  • java实现截取PDF指定页并进行图片格式转换功能

    java实现截取PDF指定页并进行图片格式转换功能

    这篇文章主要介绍了java实现截取PDF指定页并进行图片格式转换功能,本文通过实例代码给大家介绍的非常详细,具有一定的参考借鉴价值,需要的朋友可以参考下
    2019-09-09
  • springboot 基于Tomcat容器的自启动流程分析

    springboot 基于Tomcat容器的自启动流程分析

    这篇文章主要介绍了springboot 基于Tomcat容器的自启动流程分析,Spring通过注解导入Bean大体可分为四种方式,我们主要来说Import的两种实现方法,需要的朋友可以参考下
    2020-02-02
  • Java实现微信公众号自定义菜单的创建方法示例

    Java实现微信公众号自定义菜单的创建方法示例

    这篇文章主要介绍了Java实现微信公众号自定义菜单的创建方法,结合实例形式分析了java创建微信公众号自定义菜单的具体步骤、实现方法及相关操作注意事项,需要的朋友可以参考下
    2019-10-10
  • SpringBoot中配置Web静态资源路径的方法

    SpringBoot中配置Web静态资源路径的方法

    这篇文章主要介绍了SpringBoot中配置Web静态资源路径的方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-09-09

最新评论