这个是之前整理之前所学时与使用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 设置默认路由

    加入 {path: '/', redirect: 'ratings'},vue 1.0版本版本使用go,但是在2.0中是用router.go(‘/ratings’);会一直刷新

  2. Hihocoder1061-Beautiful String

    时间限制:10000ms单点时限:1000ms内存限制:256MB 描述 We say a string is beautiful if it has the equal amount of 3 or ...

  3. tinymce原装插件源码分析(七)-使能css、script

    在tinymce中使用css个script tinymce的编辑器中css和script默认是不起作用的.(编辑器主要面向写文章使用,考虑到xss攻击,默认是不启用的) 需要修改tinymce.js中 ...

  4. [NOIP2004提高组]虫食算

    题目:洛谷P1092.codevs1064.Vijos P1099. 题目大意:给你一个$n$进制.每个数都是$n$位的三个数a,b,c,这些数的数位由字母表示(共$n$个字母,从‘A’开始),所有数 ...

  5. Memcached的实战笔记

    官网:http://memcached.org/ 优秀Blogs: http://blog.csdn.net/jingqiang521/article/details/48345021 开启telne ...

  6. HDU 4253 Two Famous Companies

    Two Famous Companies Time Limit: 15000ms Memory Limit: 32768KB This problem will be judged on HDU. O ...

  7. HDU 4336

    概率DP期望,逆推即可.使用状态压缩. 注意,要全部输出...看DIS才发现题目输出是个坑.. #include <iostream> #include <cstdio> #i ...

  8. HDU 1521

    指数型生成函数.做这题时,回去看看组合数学才知道,指数生成函数求的就是多重集合的r排列数. #include <iostream> #include <cstdio> #inc ...

  9. mysql字符集修改(ubuntu)

    1.关闭mysql服务 /etc/init.d/mysql start|stop 2.在/etc/mysql/my.cnf,添加下列信息 [client] default-character-set= ...

  10. Excel数据导入___你hold住么(一)

    近期小编跟着团队一起开发ITOO3.0高校云平台项目,当中的收获是不言而喻滴,在项目中有个导入功能:导入学生信息:导入班级信息:导入教学楼信息等,在不知多少次的尝试之下,成功实现功能. 框架分析 详解 ...