java实现图片上传至本地实例详解
作者:陌上桑花开花 时间:2023-06-09 03:49:18
在工作中要求将图片上传至本地,如下代码将介绍如何将图片上传至本地
准备工作:
环境:eclipse4.5-x64,jdk1.7-x64,maven3
tomcat服务器配置图片上传映射:
上传至本地服务器配置文件:image.properties
#\u672c\u5730\u670d\u52a1\u5668\u56fe\u7247\u4fdd\u5b58\u8def\u5f84
IMAGEPATH=/mall/upload/image/
#\u56fe\u7247\u540e\u7f00\u540d
FILE_EXTEND_NAME=gif,jpg,jpeg,png,bmp
#\u672c\u5730\u670d\u52a1\u5668\u89c6\u9891\u5b58\u50a8\u5730\u5740
MEDIAPATH=/mall/upload/media/
#\u89c6\u9891\u540e\u7f00\u540d
MEDIA_EXTEND_NAME=mp4
controlle:UploadUtil.java
/**
* 文件上传工具类
* @author sang
*/
@Controller
public class UploadUtil {
/** 记录日志对象 */
private static final MyLogger LOGGER = new MyLogger(UploadUtil.class);
/**图片格式错误信息*/
private static final String LOGGERINFO1 = "的图片不符合限制";
/**
* 备注:
* uploadImgLocal,uploadImgOSS,ossConfMapper均是静态成员变量
* 则添加注解注意只能用@Autowired且get,set方法不能有static否则报错
* */
/**文件上传:本地,注意*/
private static UploadImgLocal uploadImgLocal;
/**文件上传:OSS对象 */
private static UploadImgOSS uploadImgOSS;
/**OSS配置查询 */
private static OSSConfMapper ossConfMapper;
public UploadImgLocal getUploadImgLocal() {
return uploadImgLocal;
}
@Autowired
public void setUploadImgLocal(UploadImgLocal uploadImgLocal) {
UploadUtil.uploadImgLocal = uploadImgLocal;
}
public UploadImgOSS getUploadImgOSS() {
return uploadImgOSS;
}
@Autowired
public void setUploadImgOSS(UploadImgOSS uploadImgOSS) {
UploadUtil.uploadImgOSS = uploadImgOSS;
}
public OSSConfMapper getOssConfMapper() {
return ossConfMapper;
}
@Autowired
public void setOssConfMapper(OSSConfMapper ossConfMapper) {
UploadUtil.ossConfMapper = ossConfMapper;
}
/**
* 上传文件:去除85这个宽度
* @param muFile 上传文件
* @param req
* @return Map 返回中 key值{0,1,2,oldimg} 0小图 1中图 2大图 oldimg原图
*/
public static synchronized Map<String, String> uploadFile(MultipartFile muFile,HttpServletRequest req) {
Map<String, String> map = null;
try {
//查询oss启用状态的配置信息
OSSConf ossConf=ossConfMapper.findByOssStatus();
if(muFile != null && muFile.getSize()>0 && ossConf!=null) {
//检查上传的图片的大小和扩展名
if (!UploadImgCommon.checkFileForSpringUpload(muFile)) {
throw new RuntimeException("上传" + muFile.getOriginalFilename() + LOGGERINFO1);
}
//oss类型0本地1阿里云2京东云
String ossType=ossConf.getOssType();
if("0".equals(ossType)){
//上传本地
map = uploadImgLocal.uploadForABCSize(muFile);
}else if("1".equals(ossType) || "2".equals(ossType)){
//上传oss
map=uploadImgOSS.uploadForABCSize(muFile,ossConf);
}
}
} catch (Exception e) {
e.printStackTrace();
LOGGER.error("上传文件失败"+e.getMessage(),e);
}
return map;
}
}
类:UploadImgLocal.java
/**
* 上传文件:本地
* @author somnus
*
*/
@Component("uploadImgLocal")
public class UploadImgLocal {
/** 记录日志对象 */
private static final MyLogger LOGGER = new MyLogger(UploadImgLocal.class);
/**获得当前项目访问的地址 */
private static String url;
@Resource(name = "SysHelperMapper")
private SysHelperMapper sysHelperMapper;
/**
* 上传文件:去除85这个宽度
* 存储原图地址如:http://127.0.0.1:8080:/mall/upload/image/20170804/1501811601145.jpg
* @param muFile
* @return Map 返回中 key值{0,1,2,oldimg} 0小图 1中图 2大图 oldimg原图
*/
public Map<String, String> uploadForABCSize(MultipartFile muFile) {
//封装结果集
Map<String, String> imgMap = new HashMap<String, String>();
//服务器本地保存图片路径
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
//获得当前项目访问的地址:http://127.0.0.1:8080
url=UploadImgCommon.getHttpAndPort(request);
//获取上传文件的保存路径:文件拼接地址:服务器本地保存路径+文件名+后缀
String fileNamess = UploadImgCommon.getPicNamePathSuffix();
try {
File file = new File(fileNamess);
//转存文件到指定的路径
muFile.transferTo(file);
//获取原图地址
LOGGER.info(UploadImgCommon.LOGGERINFO1 + (url+fileNamess));
//存储原图地址如:/mall/upload/image/20170804/1501811601145.jpg
imgMap.put(UploadImgCommon.OLDIMG, (url+fileNamess));
//图片处理:获取宽度集合,去除85这个宽度[352, 56, 160]
int[] widths = UploadImgCommon.getImgSetOut85(sysHelperMapper.selectImageSet());
//给宽度集合升序排序
UploadImgCommon.sortWidth(widths);//[56,160,352]
//缩放文件
File zoomFile=null;
for(int i = 0; i < widths.length; i++){
//20171226新优化:将指定尺寸图片存储至本地
//缩放文件名
String zoomFileName=UploadImgCommon.picPath + UploadImgCommon.prefix + UploadImgCommon.SYMBOLS + widths[i] + UploadImgCommon.suffix;
//创建缩放文件
zoomFile=new File(zoomFileName);
//转存文件到指定的路径
muFile.transferTo(zoomFile);
//获取指定尺寸图片地址:大图352中160小56
LOGGER.info(widths[i]+UploadImgCommon.LOGGERINFO2+(url + UploadImgCommon.picPath + UploadImgCommon.prefix + UploadImgCommon.SYMBOLS + widths[i] + UploadImgCommon.suffix));
imgMap.put(i + "", (url + UploadImgCommon.picPath + UploadImgCommon.prefix + UploadImgCommon.SYMBOLS + widths[i] + UploadImgCommon.suffix));
}
} catch (IllegalStateException e) {
e.printStackTrace();
LOGGER.error(UploadImgCommon.LOGGERINFO3, e);
} catch (IOException e) {
e.printStackTrace();
LOGGER.error(UploadImgCommon.LOGGERINFO3, e);
} catch (Exception e) {
e.printStackTrace();
LOGGER.error(UploadImgCommon.LOGGERINFO3, e);
}
return imgMap;
}
}
公共方法:UploadImgCommon.java
package com.qianjiang.util.uploadutil;
import java.io.File;
import java.io.InputStream;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Properties;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.fileupload.FileItem;
import org.springframework.web.multipart.MultipartFile;
import com.qianjiang.manager.bean.ImageSet;
import com.qianjiang.util.MyLogger;
import com.qianjiang.util.UtilDate;
/**
* 文件上传公共方法
* @author somnus
*/
public class UploadImgCommon {
/** 记录日志对象 */
private static final MyLogger LOGGER = new MyLogger(UploadImgCommon.class);
/**定义图片*/
protected static final String IMAGE = "image";
/**定义视频*/
protected static final String MEDIA="media";
/**定义图片上传最大限制10MB*/
private static long maxSize = 10 * 1024 * 1024;
/**定义视频上传最大限制500MB */
private static long mediaMaxSize= 500 * 1024 * 1024;
/**定义允许上传文件扩展名 */
private static HashMap<String, String> extMap = new HashMap<String, String>();
/**文件保存路径 */
protected static String picPath;
/** 要保存的文件名 */
protected static String prefix;
/**文件后缀 */
protected static String suffix;
/**定位宽度集合循环次数*/
protected static final int THREE = 3;
/**拼接图片缩放特殊符号*/
protected static final String SYMBOLS="@";
/**图片56缩放*/
protected static final int SMALL = 56;
/**设置imgMap中返回小图key值*/
protected static final int SMALLIMG=0;
/**原图*/
protected static final String OLDIMG = "oldimg";
protected static final String LOGGERINFO1 = "原图地址:";
protected static final String LOGGERINFO2 = "尺寸的图片地址:";
protected static final String LOGGERINFO3 = "图片上传,返回key值列表错误";
//本地上传图片properties属性值
protected static final String IMAGEPATH = "IMAGEPATH";
//本地上传视频properties属性值
protected static final String MEDIAPATH = "MEDIAPATH";
/**初始化*/
static {
//允许图片扩展名
extMap.put(IMAGE, "gif,jpg,jpeg,png,bmp");
//允许视频扩展名
extMap.put(MEDIA, "mp4");
}
/**
* 获取上传文件的保存路径
* 文件拼接地址:服务器本地保存路径+文件名+后缀
* @return 文件名(全路径)
*/
public static String getPicNamePathSuffix() {
String fileName="";
try {
//根据系统当前时间生成上传后保存的文件名
long now = System.currentTimeMillis();
//文件名系统当前时间如1501848484869
prefix = String.valueOf(now);
//文件路径如:/mall/upload/image/20170804/
picPath = getHostAndPort().getProperty(IMAGEPATH) + UtilDate.todayFormatString(new Date()) + "/";
//根据真实路径创建目录文件
File picSaveFile = new File(picPath);
if(!picSaveFile.exists()){
picSaveFile.mkdirs();
}
//文件的后缀
suffix = ".jpg";
fileName=picPath + prefix + suffix;
LOGGER.info("创建文件成功,文件名:"+fileName);
} catch (Exception e) {
e.printStackTrace();
LOGGER.error("创建本地文件失败"+e.getMessage(),e);
}
return fileName;
}
/**
* 上传视频存储本地服务器
* 获取上传文件的保存名称、服务器本地保存路径、后缀,拼接成文件地址
* @return
*/
public static String getVideoNamePathSuffix() {
String fileName="";
try {
//根据系统当前时间生成上传后保存的文件名
long now = System.currentTimeMillis();
//文件名系统当前时间如1501848484869
prefix = String.valueOf(now);
//文件路径如:/mall/upload/media/20170804/
picPath =getHostAndPort().getProperty(MEDIAPATH) + UtilDate.todayFormatString(new Date()) + "/";
//根据真实路径创建目录文件
File picSaveFile = new File(picPath);
if(!picSaveFile.exists()){
picSaveFile.mkdirs();
}
//文件的后缀(默认为MP4格式)
UploadImgCommon.suffix = ".mp4";
fileName=picPath + prefix + suffix;
LOGGER.info("创建视频文件成功,文件名:"+fileName);
} catch (Exception e) {
e.printStackTrace();
LOGGER.error("创建上传视频本地服务器地址失败:"+e.getLocalizedMessage(), e);
}
return fileName;
}
/**
* 获取宽度集合
* @return
*/
public static int[] getImgSet(List<ImageSet> imgSet) {
int[] widths = new int[imgSet.size()];
for (int i = 0; i < imgSet.size(); i++) {
widths[i] = Integer.parseInt(imgSet.get(i).getRuleWidth());
}
return widths;
}
/**
* 获取宽度集合,去除85这个宽度
* @param imgSet
* @return
*/
public static int[] getImgSetOut85(List<ImageSet> imgSet) {
int[] widths = new int[THREE];
for (int i = 0; i < imgSet.size(); i++) {
if ("85".equals(imgSet.get(i).getRuleWidth())) {
if (i < 3) {
i--;
}
continue;
}
widths[i] = Integer.parseInt(imgSet.get(i).getRuleWidth());
}
return widths;
}
/**
* 给宽度集合升序排序
* @param widths
*/
public static void sortWidth(int[] widths) {
for (int i = 0; i < widths.length; i++) {
for (int j = i + 1; j < widths.length; j++) {
int temp;
if (widths[i] > widths[j]) {
temp = widths[i];
widths[i] = widths[j];
widths[j] = temp;
}
}
}
}
/**
* 获得当前项目访问的地址
* 比如http://127.0.0.1:8080
* @param request
* @return 返回当前项目访问的地址
*/
public static String getHttpAndPort(HttpServletRequest request) {
return request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort();
}
/**
* 读取配置文件信息
* @return
*/
public static Properties getHostAndPort() {
Properties p = new Properties();
try{
InputStream inputStream = UploadImgCommon.class.getClassLoader().getResourceAsStream("config/image.properties");
p.load(inputStream);
}catch(Exception e){
e.printStackTrace();
LOGGER.error("读取Properties属性文件错误"+e.getMessage(),e);
}
return p;
}
/**
* SpringMVC上传:验证上传图片的大小和扩展名
* @param muFile 上传文件
* @return 验证通过返回true,否则返回false
*/
public static boolean checkFileForSpringUpload(MultipartFile muFile) {
boolean bool = true;
// 检查文件大小
if (muFile.getSize() > maxSize) {
LOGGER.error("=============>上传" + muFile.getOriginalFilename() + "文件大小超过限制");
bool = false;
return bool;
}
String fileName = muFile.getOriginalFilename();
//检查扩展名
String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
if (!Arrays.<String> asList(extMap.get(IMAGE).split(",")).contains(fileExt)) {
LOGGER.error("上传文件" + muFile.getOriginalFilename() + "扩展名是不允许的扩展名。\n只允许" + extMap.get(IMAGE) + "格式。");
bool = false;
return bool;
}
return bool;
}
/**
* js引入Kindeditor插件实现文件上传
* 验证上传文件大小和扩展名
* @param file 上传文件
* @return 验证通过返回true,否则返回false
*/
public static boolean checkFileAndMedia(FileItem file,String dirName) {
boolean bool = true;
//文件大小
long fileSize = file.getSize();
//文件名
String fileName = file.getName();
//检查文件大小
if(fileSize > maxSize && fileSize > mediaMaxSize){
LOGGER.error("=============>上传" + file.getFieldName() + "文件大小超过限制");
bool = false;
return bool;
}
//检查扩展名
String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
if(!Arrays.<String>asList(extMap.get(dirName).split(",")).contains(fileExt)){
LOGGER.error("上传文件" + file.getFieldName() + "扩展名是不允许的扩展名。\n只允许" + extMap.get(dirName) + "格式。");
bool = false;
return bool;
}
return bool;
}
}
上传成功后控制台打印信息:
上传成功后前台展示效果:
来源:https://blog.csdn.net/u014079773/article/details/79763325
标签:java,图片上传
0
投稿
猜你喜欢
Java多线程死锁与资源限制操作
2023-08-31 05:54:30
java String校招面试题过程详解
2021-12-01 11:11:21
WPF自定义选择年月控件详解
2021-09-05 23:48:34
浅析C#中StringBuilder类的高效及与String的对比
2022-09-14 15:54:04
C#函数式编程中的惰性求值详解
2022-01-27 03:07:29
Java ThreadLocal的使用详解
2023-11-29 04:48:43
android时间选择控件之TimePickerView使用方法详解
2023-01-14 02:58:12
使用AOP拦截Controller获取@PathVariable注解传入的参数
2023-04-30 21:42:09
HttpWebRequest出错.Section=ResponseHeader Detail=CR
2022-07-11 22:10:10
关于springboot配置druid数据源不生效问题(踩坑记)
2021-08-04 13:46:08
mybatis trim标签的使用详解
2022-07-10 23:27:54
Spring创建bean实例的几种方式分享
2022-02-21 22:08:19
C# 打开电子邮件软件的具体方法
2022-07-02 10:53:07
Mybatis注解实现多数据源读写分离详解
2021-12-15 21:44:16
C# GDI+实现时钟表盘
2023-06-20 07:11:32
Java实现打印二叉树所有路径的方法
2021-07-13 15:52:57
C#实现贪吃蛇小游戏
2022-09-28 17:17:59
SpringCloud超详细讲解负载均衡组件Ribbon源码
2021-06-17 18:39:47
android如何获取view在布局中的高度与宽度详解
2023-08-14 17:17:51
C#读写指定编码格式的文本文件
2023-06-16 03:45:41