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 ...
随机推荐
- ubuntu16.04 安装配置matlab+python +cuda8.0+cudnn+opencv3.1的caffe环境
网络上有很多ubuntu上caffe配置环境的帖子,本人照着其中的许多进行了参考,都出现了或多或少的错误,很多地方也有差异. 于是自己整理了下自己的安装过程,成功进行了测试,跑通了faster-rcn ...
- Python中zip()与zip(*)的用法
目录 Python中zip()与zip(*)的用法 zip() 知识点来自leetcode最长公共前缀 Python中zip()与zip(*)的用法 可以看成是zip()为压缩,zip(*)是解压 z ...
- web前后端安全问题
1. 安全问题主要可以理解为以下两方面: 私密性:资源不被非法窃取和利用,只有在授权情况下才可以使用: 可靠性:资料不会丢失.损坏及篡改: 2. web安全的层面 代码层面:写代码时保证代码是安全的, ...
- 全面的framebuffer详解
一.FrameBuffer的原理 FrameBuffer 是出现在 2.2.xx 内核当中的一种驱动程序接口. Linux是工作在保护模式下,所以用户态进程是无法象DOS那样使用显卡BIO ...
- Unity 多场景打包
本文章由cartzhang编写,转载请注明出处. 所有权利保留. 文章链接:http://blog.csdn.net/cartzhang/article/details/50580641 作者:car ...
- [terry笔记]python FTP
如下是作业,用python做一个ftp,主要利用socket. server端在linux下运行,在client端可以执行shell命令(静态的) 在client端输入get xxx,即可下载. 在c ...
- static方法调用
Static方法调用,类名.方法名 int number = Integer.ParseInt(String ); 将字符串参数作为有符号的十进制整数进行解析 将数字解析成字节数组 Character ...
- Eclipse配置Maven私服
Eclipse配置Maven私服 前言: 搭建Maven私有仓库的主要目的,是为了在团队多人开发时,只要内网的私有仓库有下载过依赖的jar包,就直接从私有仓库获取,不再通过外网的中央仓库.如果私服上面 ...
- android canvas 画图笔记
android canvas 画图笔记 1.PathEffect类 画虚线 Paint p = new Paint(Paint.ANTI_ALIAS_FLAG); p.setStyle(Paint.S ...
- nyoj 1189 yougth和他的朋友们 (DP)
题目:pid=1189" target="_blank">nyoj 1189 yougth和他的朋友们 这题目是14年北京赛区的原题.讲题的时候说有三种解法,我们是 ...