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

时间:2022-04-21 17:23:20

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

准备工作:

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

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

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

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

上传至本地服务器配置文件:image.properties

?
1
2
3
4
5
6
7
8
9
10
11
#\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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
/**
 * 文件上传工具类
 * @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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
/**
 * 上传文件:本地
 * @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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
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实现图片上传至本地实例详解

 

原文链接:https://blog.csdn.net/u014079773/article/details/79763325