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

 更新时间:2015年03月12日 14:43:28   投稿:hebedich  
本文给大家介绍的是项目中经常需要用到的一个常用的功能,使用java实现文件的上传下载和图片的压缩功能,这里推荐给大家,有需要的小伙伴参考下。
(福利推荐:【腾讯云】服务器最新限时优惠活动,云服务器1核2G仅99元/年、2核4G仅768元/3年,立即抢购>>>:9i0i.cn/qcloud

(福利推荐:你还在原价购买阿里云服务器?现在阿里云0.8折限时抢购活动来啦!4核8G企业云服务器仅2998元/3年,立即抢购>>>:9i0i.cn/aliyun

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

复制代码 代码如下:

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;
    }
}

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

相关文章

  • MQ的消息模型及在工作上应用场景

    MQ的消息模型及在工作上应用场景

    这篇文章主要介绍了MQ的消息模型及在工作上应用场景,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2022-05-05
  • Map集合之HashMap的使用及说明

    Map集合之HashMap的使用及说明

    这篇文章主要介绍了Map集合之HashMap的使用及说明,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-10-10
  • 软件开发基础之设计模式概述

    软件开发基础之设计模式概述

    这篇文章介绍了软件开发基础之设计模式,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2022-09-09
  • 详解Javascript判断Crontab表达式是否合法

    详解Javascript判断Crontab表达式是否合法

    这篇文章主要介绍了详解Javascript判断Crontab表达式是否合法的相关资料,需要的朋友可以参考下
    2017-03-03
  • ShardingJdbc读写分离的BUG踩坑解决

    ShardingJdbc读写分离的BUG踩坑解决

    这篇文章主要为大家介绍了ShardingJdbc读写分离的BUG踩坑解决,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2022-08-08
  • Java中File文件操作类的超详细使用教程

    Java中File文件操作类的超详细使用教程

    File类在包java.io.File下、代表操作系统的文件对象(文件、文件夹),File类提供了诸如:定位文件,获取文件本身的信息、删除文件、创建文件(文件夹)等功能,下面这篇文章主要给大家介绍了关于Java中File文件操作类的超详细使用教程,需要的朋友可以参考下
    2023-01-01
  • Java内部类的继承(全)

    Java内部类的继承(全)

    这篇文章主要介绍了Java内部类的继承,大家都知道JAVA内部类的构造器必须连接指向其外围类对象的引用,所以在继承内部类的时候,需要在导出类的构造器中手动加入对基类构造器的调用,需要的朋友可以参考下
    2015-07-07
  • springboot常用注释的讲解

    springboot常用注释的讲解

    今天小编就为大家分享一篇关于springboot常用注释的讲解,小编觉得内容挺不错的,现在分享给大家,具有很好的参考价值,需要的朋友一起跟随小编来看看吧
    2019-04-04
  • idea项目debug模式启动,断点失效,断点红点内无对勾问题及解决

    idea项目debug模式启动,断点失效,断点红点内无对勾问题及解决

    这篇文章主要介绍了idea项目debug模式启动,断点失效,断点红点内无对勾问题及解决方案,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2023-10-10
  • SpringBoot+SpringCache实现两级缓存(Redis+Caffeine)

    SpringBoot+SpringCache实现两级缓存(Redis+Caffeine)

    这篇文章主要介绍了SpringBoot+SpringCache实现两级缓存(Redis+Caffeine),文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2021-04-04

最新评论

?


http://www.vxiaotou.com