java上传文件工具类
这个是之前整理之前所学时与使用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上传文件工具类的更多相关文章
- java ftp上传文件 工具类
package com.learning.spboot.utils; import com.jcraft.jsch.*; import org.apache.commons.net.ftp.FTPCl ...
- js上传文件工具类
个人博客 地址:http://www.wenhaofan.com/article/20180808210417 jQuery.extend({ uploadUtil:function(){ } }); ...
- FTP上传-封装工具类
import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import ja ...
- ftp上传下载工具类
package com.taotao.utils; import java.io.File; import java.io.FileInputStream; import java.io.FileNo ...
- java 上传文件到 ftp 服务器
1. java 上传文件到 ftp 服务器 package com.taotao.common.utils; import java.io.File; import java.io.FileInpu ...
- java 上传文件到FTP(centos中的ftp服务)
ftp服务器系统:centos7 提供ftp的服务:vsftpd pom.xml 依赖 <dependency> <groupId>commons-net</groupI ...
- java上传文件夹文件
这里只写后端的代码,基本的思想就是,前端将文件分片,然后每次访问上传接口的时候,向后端传入参数:当前为第几块文件,和分片总数 下面直接贴代码吧,一些难懂的我大部分都加上注释了: 上传文件实体类: 看得 ...
- Java上传文件FTP服务器代码
1. 在实际的应用重,通常是通过程序来进行文件的上传. 2. 实现java上传文件到ftp服务器中 新建maven项目 添加依赖 <dependency> <groupId>c ...
- Spring MVC文件上传下载工具类
import java.io.File; import java.io.IOException; import java.io.UnsupportedEncodingException; import ...
随机推荐
- WCF(二)配置文件
上篇文章中对WCF的配置放到App.config中,这样可以使程序更灵活.更具有扩展性. 下面说下配置文件中各个节点的含义. 服务端: WCF配置文件节点放在<system.serviceMod ...
- swfupload组件上传文件
前段时间做文件上传用的是H5的一个插件,由于浏览器的兼容性不好,所以又换了一个Flash版本的上传文件插件,感觉这个上传插件的使用方式跟H5的差不多,有些雷同.不过,由于后续浏览不再支持Flash(略 ...
- struct和class两个关键字的区别
1. <C++ Primer> 用class和struct关键字定义类的唯一差别在于默认访问级别:默认情况下,struct的成员为public,而class的成员为private. 2. ...
- CPU VS GPU
CPU VS GPU 关于绘图和动画有两种处理的方式:CPU(中央处理器)和GPU(图形处理器).在现代iOS设备中,都有可以运行不同软件的可编程芯片,但是由于历史原因,我们可以说CPU所做的工作都在 ...
- 史上最低,低到尘埃,CDR邀你一起嗨购618
盼呀盼,望穿秋水~盼呀盼,何时降价~ 6.4开始,CDR X6全民狂欢618放价活动全面开启 力度之大,范围之广,时间之久,价格之低,都是前所未有的 不负众望,这个618,CDR真的做到一降到底,没有 ...
- node——将用户提交的数据写入data.json文件
前续 当我们在进行将数据提交到某个网页时,需要将提交数据保存下来 1.提交数据 2.获得数据 3.保存数据 先看提交数据: <!DOCTYPE html> <html lang=&q ...
- python matplotlib数据可视化
#基于python3 Matplotlib构建的3D图形: 使用pycharm的小伙伴把sciview给关掉: 因为sciview显示的是png图片.3d图形一般我们都需要拖拖拽拽的. 参见: htt ...
- python3三级菜单的访问,并按q退出
#/usr/bin/env python#yehui'''作业三:多级菜单 三级菜单 可依次选择进入各子菜单 所需新知识点:列表.字典'''import readlineclass MultiLeve ...
- java实现多个数字求和_图形化界面
一,设计思想 1,通过简单的窗口实现多个数字的输入与输出. 2,可通过用户输入数字的数量来实现多个数字的求和. 3,定义整型数组变量number和字符串型数组变量integer,将输入的字符串变量赋给 ...
- python hashlib、configparse、logging
一.hashlib 1.Python的hashlib提供了常见的摘要算法,如MD5,SHA1等等. 2.摘要算法 通过摘要函数f()对任意长度的数据data计算出固定长度的摘要digest,目 ...