java实现文件上传下载和图片压缩代码示例
作者:hebedich 发布时间:2023-01-02 17:49:30
标签: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;
}
}


猜你喜欢
- 前言去重,对于很多场合必不可少。写此篇文章是因为在之前做某个画面中,我在数据库中进行 Distinct 和 Order By 去重,发现影响
- 一、前言(吐槽+煽情+简介) &n
- 在开发的过程中,往往会需要在组件中添加一些按钮,用于执行一些自定义的操作。例如你有一个组件A,里面有一个List<Collider&g
- 本文实例讲述了Android模拟器实现手机添加文件到sd卡的方法。分享给大家供大家参考,具体如下:在DDMS中直接添加文件到模拟器sd卡如果
- spring通过aop获取方法参数和参数值自定义注解package com.xiaolc.aspect; import java
- 什么是Java泛型Java 泛型(generics)是 Jdk 5 中引入的一个新特性, 泛型提供了编译时类型安全检测机制, 该机制允许程序
- 前言在项目中一般使用使用volley方式如下,用起来给人一种很乱的感觉,于是一种盘它的想法油然而生。public void get() {S
- 做Android开发两年的时间,技术稍稍有一些提升,刚好把自己实现的功能写出来,记录一下,如果能帮助到同行的其他人,我也算是做了件好事,哈哈
- 什么是RESTful APIRESTful API是一种基于HTTP协议的Web API,它的设计原则是简单、可扩展、轻量级、可缓存、可靠、
- 本文实例讲述了C#实现自定义Dictionary类。分享给大家供大家参考。具体如下:1.关于MyDictionary类本文中实现的MyDic
- 自定义注解1) 先定义布局文件注入//注解的作用域在类上@Target(ElementType.TYPE)//让保持性策略为运行时态,将注解
- 从Java 5开始 引入了 JConsole。JConsole 是一个内置 Java 性能分析器,可以从命令行或在 GUI shell 中运
- 本文实例为大家分享了Unity3D仿写Button面板事件绑定功能的具体代码,供大家参考,具体内容如下最近在做一个情节引导得项目。其中一个需
- 1、注解是什么Java 注解用于为 Java 代码提供元数据,看完这句话也许你还是一脸懵逼,用人话说就是注解不直接影响你的代码执行,仅提供信
- 背景项目中经常会用到消息推送功能,关于推送技术的实现,我们通常会联想到轮询、comet长连接技术,虽然这些技术能够实现,但是需要反复连接,对
- 方法一:利用两个指针p,q,首先将q往链表尾部移动n位,然后再将p、q一起往后移,那么当q达到链表尾部时,p即指向链表的倒数第n个节点。no
- 首先声明一点,这里的重试并不是报错以后的重试,而是负载均衡客户端发现远程请求实例不可到达后,去重试其他实例。@Bean@LoadBalanc
- 指定相关的测试代码首先,写一个用于测试的关于Main(String[] args)参数输入有关的代码类,如下:using System;pu
- ArrayList集合的创建非泛型创建ArrayList集合对象,可以添加任意Object子类元素至集合//非泛型创建的ArrayList集
- 使用匿名内部类课使代码更加简洁、紧凑,模块化程度更高。内部类能够访问外部内的一切成员变量和方法,包括私有的,而实现接口或继承类做不到。然而这