后端

示例-FileController.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
@Controller
public class FileController {
/**
* 一次上传多个图片-files
*
* @param entity
* @return
*/
@RequestMapping(value = "/uploadFiles", method = RequestMethod.POST)
@ResponseBody
public ResponseBean uploadFiles(FilesuploadReq entity) {
ResponseBean resultRes = new ResponseBean();
int code = ResponseBean.CODE_SUCCESS;
String msg = "上传成功";

if (StringUtils.isEmpty(entity.getModule())) {
msg = "module 参数不能为空";
code = ResponseBean.CODE_FAILED;
resultRes.setCode(code);
resultRes.setMsg(msg);
return resultRes;
}

MultipartFile[] files = entity.getFiles();
List<String> imgs = new ArrayList<>();
File dest = null;
try {
for (int i = 0; i < files.length; i++) {
String fileName = files[i].getOriginalFilename();

String tempFilePath = FileGenerator.getFilePath(entity, fileName);
dest = new File(Constants.PRO_REAL_PATH + tempFilePath);
files[i].transferTo(dest);
imgs.add(tempFilePath);
}
} catch (IOException e) {
code = ResponseBean.CODE_FAILED;
msg = "上传失败:" + e.getMessage();
if (dest != null) {
try {
FileUtils.forceDelete(dest);
} catch (IOException ee) {
ee.printStackTrace();
}
}
e.printStackTrace();
} finally {
resultRes.setCode(code);
resultRes.setMsg(msg);
String join = String.join(",", imgs);
resultRes.setData(join);
resultRes.setSrc(join);
}

return resultRes;
}

@RequestMapping("/delete")
@ResponseBody
public ResponseBean delete(HttpServletRequest request) {
ResponseBean resultRes = new ResponseBean();
String paths = request.getParameter("paths");
if (paths != null && !"".equals(paths)) {
String[] pathArr = paths.split(",");
for (String path : pathArr) {
File file = new File(Constants.PRO_REAL_PATH + path);
try {
FileUtils.forceDelete(file);
} catch (IOException e) {
e.printStackTrace();
}
}
}

resultRes.setCode(ResponseBean.CODE_SUCCESS);
resultRes.setMsg("删除成功");
return resultRes;
}
}

依赖类

ResponseBean.java

1
2
3
4
5
6
7
8
9
10
@Data
public class ResponseBean {
private int code;
private String msg;
private Object data;
private String src;

public static int CODE_SUCCESS = 200;
public static int CODE_FAILED = -1;
}

FilesuploadReq.java

1
2
3
4
5
6
7
8
9
@Data
public class FilesuploadReq {
private String project;
private String module;

//文件名重命名: 1-是 0或空-否
private String changename;
private MultipartFile[] files;
}

FileGenerator.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
public class FileGenerator {

//文件名重命名
public static String CHANGENAME = "1";

/**
* 获得一个 UUID
* @return String UUID
*/
private static String getUUID(){
String s = UUID.randomUUID().toString();
// 去掉 “-” 符号
return s.replaceAll("-", "");
}

private static String getYMD() {
LocalDate localDate = LocalDate.now();
int year = localDate.getYear();
int monthValue = localDate.getMonthValue();
int dayOfMonth = localDate.getDayOfMonth();

return year + "/" + monthValue + "/" + dayOfMonth;
}

/**
* 获取文件路径
* @param entity
* @param originalFilename
* @return
*/
public static String getFilePath(FilesuploadReq entity, String originalFilename) {
StringBuilder tempath = new StringBuilder("/");
if(!StringUtils.isEmpty(entity.getProject())) {
tempath.append(entity.getProject());
tempath.append("/");
}
tempath.append(entity.getModule() + "/" + getYMD());
String path = Constants.PRO_REAL_PATH + tempath.toString();
File file = new File(path);
if(!file.exists()) {
try {
FileUtils.forceMkdir(file);
} catch (IOException e) {
e.printStackTrace();
}
}

String filename = originalFilename;
String changename = entity.getChangename();
if(CHANGENAME.equals(changename)) {
String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
filename = getUUID() + suffix;
}

return tempath.toString() + "/" + filename;
}
}

前端

示例-index.html

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
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>上传图片插件</title>
<link href="../src/css/jquery.upload.css" type="text/css" rel="stylesheet" />
</head>
<body>
<div id="image-box"></div>

<script src="https://cdn.staticfile.org/jquery/3.1.0/jquery.min.js"></script>
<script src="../src/js/jquery.upload.js"></script>

<script>
$("#image-box").ajaxImageUpload({
fileInput : 'files',
postUrl : 'http://192.168.0.147:8080/gms-web/uploadFiles.do', //上传的服务器地址
fileServerUrl : 'http://192.168.0.147:8080/gms-web', //文件查看服务器地址
deleteUrl : 'http://192.168.0.147:8080/gms-web/delete.do', //删除文件服务地址
width : 100,
height : 100,
imageUrl: ['/upload/building/2021/6/17/288ba7fa239f4f779ac98d988798c131.jpg'],
postData : { "project":'', "module":'upload/building',"changename":1 },
maxNum: 100, //允许上传图片数量
allowZoom : true, //允许放大
allowType : ['png', 'jpg', 'jpeg', 'gif'], //允许上传图片的类型
maxSize : 10, //允许上传图片的最大尺寸,单位M
appendMethod : 'after',
before : function () {
// alert('上传前回调函数2');
},
success : function(json){
// alert('上传成功回调函数2');
console.log(json);
},
complete : function () {
// alert('全部上传成功2');
},
error : function (e) {
console.log(e);
}
});
</script>

</body>
</html>

资源文件 - css、js

jquery.upload.css

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
.ggy-section-box{margin-bottom:10px;padding:10px;border:1px dashed #e7e6e6;clear:both}
.ggy-section-box:after{content:'';display:block;clear:both}
.ggy-section-box .loading{background:url(../images/loading.gif) no-repeat center}
.ggy-section-box .ggy-image-show{display:block;width:100%;height:100%}
.ggy-section-box .ggy-image-section{border:1px dashed #e7e6e6;margin-right:10px}
.ggy-section-box .ggy-image-section:hover{border:1px solid #e7e6e6}
.ggy-image-section .ggy-image-shade{display:block;width:100%;height:100%;visibility:hidden;position:absolute;top:0;left:0;background:rgba(0,0,0,.5)}
.ggy-image-section:hover .ggy-image-shade{visibility:visible}
.ggy-image-section,.ggy-upload-section{position:relative;width:190px;height:190px;float:left;cursor: pointer;}
.ggy-upload-section .ggy-upload-input{cursor:pointer;width:100%;height:100%;opacity:0;position:absolute;top:0;left:0;z-index:100}
.ggy-upload-section .ggy-upload-icon{cursor: pointer;display:block;width:100%;height:100%;border:1px dashed #d0d0d0;background:url(../images/upload.png) no-repeat center}
.ggy-section-box .ggy-modal-section{z-index:1000;display:none;position:fixed;top:0;left:0;width:100%;height:100%;background:rgba(0,0,0,.4)}
.ggy-modal-section .ggy-modal-box{border:5px solid #fff;box-shadow:2px 2px 2px rgba(0,0,0,.2);background:#fff;text-align:center;position:absolute;top:50%;left:50%;transform:translate(-50%,-50%)}
.ggy-image-section .ggy-delete-icon{position:absolute;width:30px;height:30px;top:5px;right:5px;display:none;z-index:999;background:url(../images/delete.png) no-repeat center}
.ggy-image-section:hover .ggy-delete-icon{display:block;cursor:pointer}
.ggy-modal-section .ggy-delete-box{width:500px;height:160px}
.ggy-delete-box p{margin:0;padding:0}
.ggy-delete-box .ggy-delete-tip{color:#555;height:94px;line-height:94px;font-size:18px;border-bottom:1px solid #d1d1d1}
.ggy-delete-box .ggy-delete-btn{height:66px;line-height:66px;position:absolute;bottom:0;left:0;width:100%}
.ggy-delete-btn span{width:49.8%;display:inline-block;text-align:center;color:#d4361d;font-size:18px}
.ggy-delete-btn span:first-child{border-right:1px solid #d1d1d1}
.ggy-delete-btn:hover span{cursor:pointer}
.ggy-image-section .ggy-zoom-icon{position:absolute;width:32px;height:32px;top:40px;right:40px;display:none;z-index:999;background:url(../images/zoom.png) no-repeat center}
.ggy-image-section:hover .ggy-zoom-icon{display:block;cursor:pointer}
.ggy-zoom-box img{height:100%;width:auto;max-height:100%;max-width:100%;padding:0;display:inline-block;line-height:0;vertical-align:middle}

jquery.upload.js

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
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
"use strict";
!(function($) {
var pluginName = "ajaxImageUpload",
defaults = {
fileInput: '', // 上传按钮名,即input[type=file]的name值
postUrl: '', // POST上传地址
deleteUrl: '', //删除地址
fileServerUrl: '',
width: 150, // 图片宽度
height: 150, // 图片高度
imageUrl: [], // 已上传的图片连接
postData: {}, // 额外数据
allowZoom: true, // 是否允许缩放
allowType: ["gif", "jpeg", "jpg", "bmp", "png"],
maxNum: 5, // 最多允许上传个数
maxSize: 1, // 允许上传图片的最大尺寸,单位M
appendMethod: 'before', // 追加方式
before: $.noop, // 上传前回调函数
success: $.noop, // 上传成功时的回调函数
error: $.noop, // 上传失败时的回调函数
complete: $.noop // 所有上传完成时的回调函数
};

function Plugin(element, options) {
this.element = element;
this.settings = $.extend({}, defaults, options);
this._defaults = defaults;
this._name = pluginName;
this.complete = true;
this.code = 0;
this.msg = '';
this.init();
}

Plugin.prototype = {
init: function() {
var $self = this,
$this = $(this.element),
$imageUrl = $self.settings.imageUrl;

$self.createSectionBox();

// 已经存在的图片先展示出来
if ($imageUrl.length > 0) {
for (var $i = 0; $i < $imageUrl.length; $i++) {
$self.createImageSection($imageUrl[$i]);
}
}

$this.find("input[type=file]").on('change', function() {
$self.selectFile();
});

},
/**
* 选择文件
* @returns {boolean}
*/
selectFile: function() {
var $self = this,
$this = $(this.element),
$maxNum = $self.settings.maxNum,
$maxSize = $self.settings.maxSize,
$postUrl = $self.settings.postUrl,
$fileInput = $self.settings.fileInput,
$before = $self.settings.before,
$complete = $self.settings.complete,
$uploadInput = $this.find("input[type=file]"),
$imageSection = $this.find('.ggy-image-section');

if (!$postUrl) {
$self.callError("300", "没有配置postUrl");
$self.resetFile();
return false;
}

if (!$fileInput) {
$self.callError("301", "没有配置fileInput");
$self.resetFile();
return false;
}

if ($before && $before() === false) {
$self.resetFile();
return false;
}

var $files = $uploadInput[0].files;

if ($files.length + $imageSection.length > $maxNum) {
$self.callError("302", "上传图片数目不能超过" + $maxNum + "个");
$self.resetFile();
return false;
}

for (var $i = 0; $i < $files.length; $i++) {
var $file = $files[$i];

if (!$self.isAllowFile($file)) {
$self.callError("303", $file.name + " 图片类型不支持");
$self.resetFile();
break;
}

if ($self.getFileSize($file) > $maxSize) {
$self.callError("304", '上传图片不能超过' + $maxSize + 'M,当前上传图片的大小为' + $fileSize.toFixed(2) + 'M');
$self.resetFile();
break;
}

$self.createImageSection();
$self.ajaxUpload($file);
}

if ($self.complete == true) {
$complete();
}

$self.resetFile();
},

/**
* 创建容器盒子
* @returns {*|jQuery|HTMLElement}
*/
createSectionBox: function() {
var $self = this,
$this = $(this.element),
$fileInput = $self.settings.fileInput,
$sectionBox = $("<div class='ggy-section-box'></div>"),
$uploadSection = $("<section class='ggy-upload-section'></section>"),
$modalSection = $("<section class='ggy-modal-section'></section>"),
$uploadIcon = $("<i class='ggy-upload-icon'></i>"),
$uploadInput = $("<input type='file' name='" + $fileInput + "' class='ggy-upload-input' accept='image/*' multiple='multiple'>");

$sectionBox.appendTo($this);
$uploadSection.appendTo($sectionBox);
$uploadIcon.appendTo($uploadSection);
$uploadInput.appendTo($uploadSection);
$modalSection.appendTo($sectionBox);

$modalSection.on('click', function(event) {
event.stopPropagation();
$modalSection.hide();
});

},

/**
* 创建上传图片容器片段
* @param $src
* @returns {*|jQuery|HTMLElement}
*/
createImageSection: function($src) {
var $self = this,
$fileServerUrl = $self.settings.fileServerUrl,
$this = $(this.element),
$width = $self.settings.width,
$height = $self.settings.height,
$fileInput = $self.settings.fileInput,
$allowZoom = $self.settings.allowZoom,
$appendMethod = $self.settings.appendMethod,
$sectionBox = $this.find(".ggy-section-box"),
$uploadSection = $this.find(".ggy-upload-section"),
$imageSection = $("<section class='ggy-image-section loading'></section>"),
$imageShade = $("<div class='ggy-image-shade'></div>"),
$hiddenInput = $("<input type='hidden' name='" + $fileInput + "[]' value='" + $fileServerUrl + $src + "'>"),
$imageShow = $("<img class='ggy-image-show shade' src='" + $fileServerUrl + $src + "'/>");

if ($src) {
$imageShow = $("<img class='ggy-image-show' src='" + $fileServerUrl + $src + "'/>");
}

$imageSection.css({ 'width':$width, 'height':$height });
$uploadSection.css({ 'width':$width, 'height':$height });

switch ($appendMethod) {
case "before":
$sectionBox.prepend($imageSection);
break;
case "after":
$uploadSection.before($imageSection);
break;
}

$hiddenInput.appendTo($imageSection);
$imageShow.appendTo($imageSection);
$imageShade.appendTo($imageSection);

$self.createDeleteNode($imageSection);

if ($src && $allowZoom === true) {
$self.createZoomNode($imageSection);
}
},

createDeleteNode: function($imageSection) {
var $this = $(this.element),
$deleteUrl = this.settings.deleteUrl,
$fileServerUrl = this.settings.fileServerUrl,
$modalSection = $this.find(".ggy-modal-section"),
$deleteIcon = $("<i class='ggy-delete-icon'></i>"),
$deleteBox = $("<div class='ggy-modal-box ggy-delete-box'><p class='ggy-delete-tip'>您确定要删除吗?</p><p class='ggy-delete-btn'> <span class='ggy-confirm-btn'>确定</span><span class='ggy-cancel-btn'>取消</span></p></div>");

$deleteIcon.appendTo($imageSection);

// 点击显示删除确认弹框
let deleteSrc = "";
$imageSection.find(".ggy-delete-icon").on('click', function(event) {
event.stopPropagation();
$modalSection.html($deleteBox);
$modalSection.show();

deleteSrc = $(this).parent().find('input[type=hidden]').val();
console.log(deleteSrc)
});

// 确认删除
$deleteBox.find(".ggy-confirm-btn").on('click', function(event) {
event.stopPropagation();
$modalSection.hide();
$imageSection.remove();
$deleteBox.remove();

//删除文件
$.ajax({
url: $deleteUrl + "?paths=" + deleteSrc.replace($fileServerUrl,""),
type: 'get',
async: false,
dataType: 'json',
success: function($json) {
console.log($json);
},
error: function(jqXHR, textStatus, errorThrown) {

}
});
});

// 取消删除
$deleteBox.find(".ggy-cancel-btn").on('click', function(event) {
event.stopPropagation();
$modalSection.hide();
return false;
});
},

createZoomNode: function($imageSection) {
var $this = $(this.element),
$imageShow = $imageSection.find(".ggy-image-show"),
$modalSection = $this.find(".ggy-modal-section"),
$zoomIcon = $("<i class='ggy-zoom-icon'></i>"),
$zoomBox = $("<div class='ggy-modal-box ggy-zoom-box'><img src=''/></div>");

$zoomBox.find('img').attr('src', $imageShow.attr('src'));
$zoomIcon.appendTo($imageSection);

// 点击显示弹出框
$imageSection.find(".ggy-zoom-icon").on('click', function(event) {
event.stopPropagation();
$modalSection.html($zoomBox);
$modalSection.show();
});

},

/**
* 上传文件
* @param $file
*/
ajaxUpload: function($file) {
var $self = this,
$this = $(this.element),
$fileServerUrl = $self.settings.fileServerUrl,
$fileInput = $self.settings.fileInput,
$postData = $self.settings.postData,
$postUrl = $self.settings.postUrl,
$allowZoom = $self.settings.allowZoom,
$success = $self.settings.success,
$appendMethod = $self.settings.appendMethod;

switch ($appendMethod) {
case "before":
var $imageSection = $this.find('.ggy-image-section:first');
var $imageShow = $this.find('.ggy-image-show:first');
break;
case "after":
var $imageSection = $this.find('.ggy-image-section:last');
var $imageShow = $this.find('.ggy-image-show:last');
break;
}

var $formData = new FormData();

$formData.append($fileInput, $file);

for (var $key in $postData) {
$formData.append($key, $postData[$key]);
}

$.ajax({
url: $postUrl,
type: 'post',
async: false,
data: $formData,
processData: false,
contentType: false,
dataType: 'json',
mimeType: "multipart/form-data",
success: function($json) {
if ($json.code != 200) {
$self.callError($json.code, $json.msg);
$imageSection.remove();
return false;
}
$imageShow.removeClass("shade").attr('src', $fileServerUrl + $json.src);
$imageSection.find('input[type=hidden]').val($json.src);
if ($allowZoom === true) {
$self.createZoomNode($imageSection);
}
$self.complete *= true;
$success($json);
},
error: function(jqXHR, textStatus, errorThrown) {
$self.callError(jqXHR.status, 'AjaxUrl Service Error:' + jqXHR.statusText);
$imageSection.remove();
}
});
},

/**
* 是否允许上传文件
* @param $file
* @returns {boolean}
*/
isAllowFile: function($file) {
var $allowType = this.settings.allowType,
$fileExt = this.getFileExt($file);
if ($.inArray($fileExt, $allowType) != -1) {
return true;
}
return false;
},

/**
* 获取文件扩展名
* @param $file
* @returns {string}
*/
getFileExt: function($file) {
var $fileName = $file.name,
$index = $fileName.lastIndexOf('.');
if ($index < 1) {
return '';
}
return $fileName.substr($index + 1).toLowerCase();
},

/**
* 获取文件大小
* @param $file
* @returns {number}
*/
getFileSize: function($file) {
return ($file.size) / (1024 * 1024);
},

/**
* 重置上传域
*/
resetFile: function() {
$(this.element).find("input[type=file]").val(null);
},

/**
* 调用error函数
* @param $code
* @param $msg
*/
callError: function($code, $msg) {
var $self = this,
$error = $self.settings.error;

$self.complete *= false;

$self.code = $code;
$self.msg = $msg;
$error($self);
}
};

$.fn[pluginName] = function(options) {
return this.each(function() {
if (!$.data(this, "plugin_" + pluginName)) {
$.data(this, "plugin_" + pluginName, new Plugin(this, options));
}
});
};
})(jQuery, window, document);