这个是之前整理之前所学时与使用java向邮箱发送邮件一块找到的,一起贴出来供大家参考:

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID; import javax.imageio.ImageIO; import org.apache.struts.upload.FormFile;
import org.apache.struts.util.MessageResources;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; public class UploadFile { /**
* 按照ID和当前时间生成目录
* @param OrderId
* @return
*/
public static String getAbsolutePath(){
String currYear= new SimpleDateFormat("yyyy").format(new Date());
String currMonth= new SimpleDateFormat("MM").format(new Date());
String currDay = new SimpleDateFormat("dd").format(new Date());
String path = new StringBuffer(currYear).append('/').append(currMonth).append('/').append(currDay).append('/').toString();
return path;
} /**
* 上传课程资料
* @param dir 文件目录
* @param trueName 文件名称
* @param formFile FormFile
* @return String
* @throws Exception
*/
public static String uploadFile(int courseId,String dir,FormFile file,MessageResources message) throws Exception {
String fileName = file.getFileName();
int i = fileName.lastIndexOf(".");
String logoFormat = fileName.substring(i + 1);
int size = file.getFileSize();
// *************限制文件的上传格式和文件大小*******************
String fileFormat = message.getMessage("file.fileFormat"); // 文件格式
int imageSize = Integer.valueOf(message.getMessage("file.fileSize"));// 文件大小
String format = UploadFile.checkFileExt(logoFormat, fileFormat); // 判断文件格式
if (format != null && size <= imageSize) {
fileName = courseId+"_"+String.valueOf(System.currentTimeMillis()) + "." + logoFormat;
File dirPath = new File(dir + "/" + fileName);// 存储位置
mkdirIfNotExists(dirPath);
InputStream streamIn = file.getInputStream(); // 创建读取用户上传文件的对象
File uploadFile = new File(dir); // 创建把上传数据写到目标文件的对象
// 判断指定路径是否存在,不存在则创建路径
if (!uploadFile.exists() || uploadFile == null) {
uploadFile.mkdirs();
}
OutputStream streamOut = new FileOutputStream(dirPath);
int bytesRead = 0;
byte[] buffer = new byte[8192];
while ((bytesRead = streamIn.read(buffer, 0, 8192)) != -1) {
streamOut.write(buffer, 0, bytesRead);
}
streamOut.close();
streamIn.close();
file.destroy();
return fileName;
}else{
return null;
}
} /**
* 上传文章附件
* @param dir
* @param file
* @param message
* @return
* @throws Exception
*/
public static String uploadFile(String dir,FormFile file,MessageResources message) throws Exception {
String fileName = file.getFileName();
int i = fileName.lastIndexOf(".");
String logoFormat = fileName.substring(i + 1);
int size = file.getFileSize();
// *************限制文件的上传格式和文件大小*******************
String fileFormat = message.getMessage("file.fileFormat"); // 文件格式
int imageSize = Integer.valueOf(message.getMessage("file.fileSize"));// 文件大小
String format = UploadFile.checkFileExt(logoFormat, fileFormat); // 判断文件格式
if (format != null && size <= imageSize) {
fileName = String.valueOf(System.currentTimeMillis()) + "." + logoFormat;
File dirPath = new File(dir + "/" + fileName);// 存储位置
mkdirIfNotExists(dirPath);
InputStream streamIn = file.getInputStream(); // 创建读取用户上传文件的对象
File uploadFile = new File(dir); // 创建把上传数据写到目标文件的对象
// 判断指定路径是否存在,不存在则创建路径
if (!uploadFile.exists() || uploadFile == null) {
uploadFile.mkdirs();
}
OutputStream streamOut = new FileOutputStream(dirPath);
int bytesRead = 0;
byte[] buffer = new byte[8192];
while ((bytesRead = streamIn.read(buffer, 0, 8192)) != -1) {
streamOut.write(buffer, 0, bytesRead);
}
streamOut.close();
streamIn.close();
file.destroy();
return fileName;
}else{
return null;
}
} public static String uploadFile1(String dir,FormFile file,MessageResources message) throws Exception {
String fileName = file.getFileName();
String s=UUID.randomUUID().toString();
int i = fileName.lastIndexOf(".");
String logoFormat = fileName.substring(i + 1);
int size = file.getFileSize();
// *************限制文件的上传格式和文件大小*******************
String fileFormat = message.getMessage("file.fileFormat"); // 文件格式
int imageSize = Integer.valueOf(message.getMessage("file.fileSize"));// 文件大小
String format = UploadFile.checkFileExt(logoFormat, fileFormat); // 判断文件格式
if (format != null && size <= imageSize) {
fileName = String.valueOf(System.currentTimeMillis()+s) + "." + logoFormat;
File dirPath = new File(dir + "/" + fileName);// 存储位置
mkdirIfNotExists(dirPath);
InputStream streamIn = file.getInputStream(); // 创建读取用户上传文件的对象
File uploadFile = new File(dir); // 创建把上传数据写到目标文件的对象
// 判断指定路径是否存在,不存在则创建路径
if (!uploadFile.exists() || uploadFile == null) {
uploadFile.mkdirs();
}
OutputStream streamOut = new FileOutputStream(dirPath);
int bytesRead = 0;
byte[] buffer = new byte[8192];
while ((bytesRead = streamIn.read(buffer, 0, 8192)) != -1) {
streamOut.write(buffer, 0, bytesRead);
}
streamOut.close();
streamIn.close();
file.destroy();
return fileName;
}else{
return null;
}
} /**
* @param 文件扩展名
* @param permitFormatsConfig 文件类型
* @return String 文件匹配类型
*/
public static String checkFileExt(String type, String permitFormatsConfig) {
String[] formats = permitFormatsConfig.split(";");
for (int i = 0; i < formats.length; i++) {
if (type.toLowerCase().endsWith(formats[i].toLowerCase())) {
return formats[i];
}
}
return null;
}
public static File mkdirIfNotExists(File file) {
if (file.exists()) {
return file;
}
if (file.isDirectory() && file.mkdirs()) {
return file;
}
File parentDirectory = file.getParentFile();
if (parentDirectory.exists()) {
return file;
} else if (parentDirectory.mkdirs()) {
return file;
}
throw new java.lang.RuntimeException(
"Failed to make some necessary parent directories. Please trying.");
} /**
* 上传图片,并获得缩小图片
* 图片大小交由显示页面控制 后台将不负责修改图像大小
* @param picDir
* @param file
* @param message
* @param width
* @return
* @throws Exception
*/
public static String uploadFile(String picDir, FormFile file,
MessageResources message, int width,int height) throws Exception {
String fileName = file.getFileName();
int ff = fileName.lastIndexOf(".");
ImageScale imageScale = new ImageScale();
String logoFormat = fileName.substring(ff + 1);
int size = file.getFileSize();
// *************限制文件的上传格式和文件大小*******************
String fileFormat = message.getMessage("file.imageFormat"); // 文件格式
int imageSize = Integer.valueOf(message
.getMessage("file.imageSize"));// 文件大小
String format = UploadFile.checkFileExt(logoFormat, fileFormat); // 判断文件格式
if (format != null && size <= imageSize) {
fileName = String.valueOf(System.currentTimeMillis()) + "." + logoFormat;
File dirPath = new File(picDir + "/" + fileName);
mkdirIfNotExists(dirPath);// 存储位置
InputStream stream = file.getInputStream();
OutputStream bos = new FileOutputStream(dirPath);
BufferedImage Bi = ImageIO.read(file.getInputStream());
bos = new FileOutputStream(dirPath);
//图片大小交由显示页面控制 后台将不负责修改图像大小
/*if (Bi.getWidth() > width || Bi.getHeight() > height) {
Bi = imageScale.imageZoomOut(Bi, width, height);
ImageIO.write(Bi, logoFormat, dirPath);
} else {*/
ImageIO.write(Bi, logoFormat, dirPath);
//}
bos.close();
stream.close();
file.destroy();
return fileName;
} else {
file.destroy();
return null;
}
} /**
* 上传图片,并获得缩小图片
* @param picDir
* @param file
* @param message
* @param width
* @return
* @throws Exception
*/
public static String uploadFile(String picDir, FormFile file,MessageResources message, int width) throws Exception {
String fileName = file.getFileName();
int ff = fileName.lastIndexOf(".");
ImageScale imageScale = new ImageScale();
String logoFormat = fileName.substring(ff + 1);
int size = file.getFileSize();
// *************限制文件的上传格式和文件大小*******************
String fileFormat = message.getMessage("file.imageFormat"); // 文件格式
int imageSize = Integer.valueOf(message.getMessage("file.imageSize"));// 文件大小
String format = UploadFile.checkFileExt(logoFormat, fileFormat); // 判断文件格式
if (format != null && size <= imageSize) {
fileName = String.valueOf(System.currentTimeMillis()) + "."+ logoFormat;
File dirPath = new File(picDir + "/" + fileName);// 存储位置
mkdirIfNotExists(dirPath);
InputStream stream = file.getInputStream();
OutputStream bos = new FileOutputStream(dirPath);
BufferedImage Bi = ImageIO.read(file.getInputStream());
if (Bi.getWidth() > width || Bi.getHeight() > width) {
Bi = imageScale.imageZoomOut(Bi, width, width);
ImageIO.write(Bi, logoFormat, dirPath);
} else {
ImageIO.write(Bi, logoFormat, dirPath);
}
bos.close();
stream.close();
file.destroy();
dirPath = new File(picDir + "/hoy_" + fileName);
bos = new FileOutputStream(dirPath);
if (Bi.getWidth() > 142 || Bi.getHeight() > 60) {
Bi = imageScale.imageZoomOut(Bi, 142, 60);
ImageIO.write(Bi, logoFormat, dirPath);
} else {
ImageIO.write(Bi, logoFormat, dirPath);
}
bos.close();
stream.close();
file.destroy();
return fileName;
} else {
file.destroy();
return null;
}
}
}

java上传文件工具类的更多相关文章

  1. java ftp上传文件 工具类

    package com.learning.spboot.utils; import com.jcraft.jsch.*; import org.apache.commons.net.ftp.FTPCl ...

  2. js上传文件工具类

    个人博客 地址:http://www.wenhaofan.com/article/20180808210417 jQuery.extend({ uploadUtil:function(){ } }); ...

  3. FTP上传-封装工具类

    import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import ja ...

  4. ftp上传下载工具类

    package com.taotao.utils; import java.io.File; import java.io.FileInputStream; import java.io.FileNo ...

  5. java 上传文件到 ftp 服务器

    1.  java 上传文件到 ftp 服务器 package com.taotao.common.utils; import java.io.File; import java.io.FileInpu ...

  6. java 上传文件到FTP(centos中的ftp服务)

    ftp服务器系统:centos7 提供ftp的服务:vsftpd pom.xml 依赖 <dependency> <groupId>commons-net</groupI ...

  7. java上传文件夹文件

    这里只写后端的代码,基本的思想就是,前端将文件分片,然后每次访问上传接口的时候,向后端传入参数:当前为第几块文件,和分片总数 下面直接贴代码吧,一些难懂的我大部分都加上注释了: 上传文件实体类: 看得 ...

  8. Java上传文件FTP服务器代码

    1. 在实际的应用重,通常是通过程序来进行文件的上传. 2. 实现java上传文件到ftp服务器中 新建maven项目 添加依赖 <dependency> <groupId>c ...

  9. Spring MVC文件上传下载工具类

    import java.io.File; import java.io.IOException; import java.io.UnsupportedEncodingException; import ...

随机推荐

  1. vue <router-view>没有渲染

    将routes中的components换成component

  2. eclipse 启动程序时错误弹窗:multiple problems have occurred

    .log内容如下: !ENTRY org.eclipse.ui 4 4 2017-04-14 09:31:05.341!MESSAGE An internal error has occurred.! ...

  3. ZBrush国庆中秋大放价,优惠提前享!

    没记错的话,上次的ZBrush活动应该是17年春节吧,悄么蔫地就把端午节等一系列节日忽略了,这让苦苦等待的小伙伴们情何以堪,这试用版用的也不得劲儿! 终于等到你,ZBrush官方消息称,17年中秋国庆 ...

  4. Java自定义属性注解

    代码: import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.ElementT ...

  5. 【Django】创建后的基本操作

    1.创建Django项目做基本的配置步骤Pycharm->new->New Project 2.基本的配置settings.py-->STATIC_URL = '/static/'后 ...

  6. Iterator与Asyc/Await的实现

    https://wanago.io/2018/04/23/demystifying-generators-implementing-async-await/

  7. 洛谷4623 [COCI2012-2013#6] BUREK

    题目描述 给定N个三角形,和M条直线,直线要么平行于X轴,要么平行于Y轴,问这M条直线 分别经过多少个三角形内部 (注意是内部即分开的两个多边形的面积均大于零). 输入输出格式 输入格式: 第一行一个 ...

  8. POJ 1988 Cube Stacking( 带权并查集 )*

    POJ 1988 Cube Stacking( 带权并查集 ) 非常棒的一道题!借鉴"找回失去的"博客 链接:传送门 题意: P次查询,每次查询有两种: M x y 将包含x的集合 ...

  9. ASP.NET-EF基础知识

    定义 asp.net Entity Framework是微软以ADO.NET为基础发展出来的对象关系对应(OR Mapping)解决方案.   三种EF工作模式(自己理解的) 从数据库表创建类 从类创 ...

  10. Oracle性能分析1:开启SQL跟踪和获取trace文件

    当Oracle查询出现效率问题时,我们往往须要了解问题所在,这样才干针对问题给出解决方式.Oracle提供了SQL运行的trace信息,当中包括了SQL语句的文本信息.一些运行统计,处理过程中的等待, ...