亲宝软件园·资讯

展开

java实现图片上传至本地 java实现图片上传至本地实例详解

陌上桑花开花 人气:0

在工作中要求将图片上传至本地,如下代码将介绍如何将图片上传至本地

准备工作:

环境: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;
 }
 
 
 
}

上传成功后控制台打印信息:

上传成功后前台展示效果:

加载全部内容

相关教程
猜你喜欢
用户评论