欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2024-02-23 16:56:10
在工作中要求将图片上传至本地,如下代码将介绍如何将图片上传至本地 准备工作: 环境:eclipse4.5-x64,jdk1.7-x64,maven3 tomcat服务...

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

准备工作:

环境:eclipse4.5-x64,jdk1.7-x64,maven3

tomcat服务器配置图片上传映射:

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

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

上传至本地服务器配置文件: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;
 }
 
 
 
}

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

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

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

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

上一篇: 高效的jsp分页查询

下一篇: