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 ...
随机推荐
- 『转』Writing Well
这是前辈Julie Zhuo的最新关于写作的文章,昨天写下-进行总结和阅读思考 这是一篇关于提笔写作的文章,首发在The looking glass...前辈每周都会回答一个读者的问题耶--This ...
- UVa 11520 Fill in the Square
题意:给出 n*n的格子,把剩下的格子填上大写字母,使得任意两个相邻的格子的字母不同,且从上到下,从左到右的字典序最小 从A到Z枚举每个格子填哪一个字母,再判断是否合法 #include<ios ...
- 鼠标悬浮触发事件(onmouseover)实现
将鼠标移至(悬浮)到某个标签范围内触发事件或提示消息等效果实现的关键词为:onmouseover. 代码: <!DOCTYPE html> <html> <head> ...
- PAT 天梯赛练习集 L1-006. 连续因子
题目链接:https://www.patest.cn/contests/gplt/L1-006 一个正整数N的因子中可能存在若干连续的数字.例如630可以分解为3*5*6*7,其中5.6.7就是3个连 ...
- 对于 wepy 不是内部或外部命令 -- 的解决办法
闲来没事继续研究自己之前一直未解决的问题, 就是自己笔记本安装wepy-cli,一直提示"wepy 不是内部或外部命令". 因为公司里面用的是这个框架, 想着自己在家没事的时候去 ...
- php5 中魔术方法函数有哪几个
魔术函数:9.3 构造函数:__construct() 9.3.1 实例化对象时被调用. 9.3.2 在类中,构造函数是用来初始化对象的,利用构造函数,可以操作对象,并改变它的值. 9.3.3 当__ ...
- code-reading-notes--libyang-1
API struct lyd_node * lyd_parse_xml(struct ly_ctx *ctx, struct lyxml_elem **root, int options, ...) ...
- 微信支付报ip错,怀疑是因为不能正确获取$_Server[addr])ip导致的
报如下错误,应该是本地测试环境不能正确获取客户ip导致的错误 果然 放到服务器上在测试就好了
- Spring IOC过程
https://www.processon.com/diagraming/5c96171fe4b0f88919b98497 1. AbstractApplicationContext:执行refres ...
- 洛谷——P1351 联合权值
https://www.luogu.org/problem/show?pid=1351 题目描述 无向连通图G 有n 个点,n - 1 条边.点从1 到n 依次编号,编号为 i 的点的权值为W i , ...