本文实例为大家分享了springMVC图片上传的处理方式,供大家参考,具体内容如下
首先需要依赖的jar包:
1
2
3
4
5
6
7
8
9
10
|
< dependency >
< groupId >commons-io</ groupId >
< artifactId >commons-io</ artifactId >
< version >1.3.2</ version >
</ dependency >
< dependency >
< groupId >commons-fileupload</ groupId >
< artifactId >commons-fileupload</ artifactId >
< version >1.2.1</ version >
</ dependency >
|
页面:
1
2
3
|
< a href = "javascript:;" rel = "external nofollow" class = "a-upload" >
< input class = "" type = "file" name = "file" id = "file" required = "required" >上传
</ a >
|
大家如果觉得默认的上传文件的按钮不好看,可以引入下面的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
26
27
|
.a-upload {
padding : 4px 10px ;
height : 27px ;
line-height : 27px ;
position : relative ;
cursor : pointer ;
color : #888 ;
background : #fafafa ;
border : 1px solid #ddd ;
border-radius: 4px ;
overflow : hidden ;
}
.a-upload input {
position : absolute ;
width : 100% ;
right : 0 ;
top : 0 ;
opacity: 0 ;
filter: alpha(opacity= 0 );
cursor : pointer
}
.a-upload:hover {
color : #444 ;
background : #eee ;
border-color : #ccc ;
text-decoration : none
}
|
前端脚本:
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
|
$( '#file' ).on( 'change' , function () {
var $ this = $( this );
var formData = new FormData();
formData.append( 'file' , $( '#file' )[0].files[0]);
var fileName = $( '#file' )[0].files[0].name;
var fileType = fileName.substring(fileName.lastIndexOf( '.' ) + 1);
var fileSize = $( '#file' )[0].files[0].size;
if (fileType != 'jpg' && fileType != 'png' && fileType != 'gif' ) {
alert( "请上传.jpg、.png、.gif格式的图片!" );
return ;
}
if (fileSize > 300 * 1024) {
alert( "请上传大小小于300KB的图片!" );
return ;
}
$.ajax({
url: '/admin/upload' ,
type: 'POST' ,
data: formData,
cache: false ,
processData: false ,
contentType: false
}).done( function (result) {
if (result != '' ) {
$ this .closest( 'div' ).append( '<div class="img-preview"><img src="' + result + '"/></div>' );
} else {
alert( "请上传.jpg、.png、.gif格式的图片!" );
}
}).fail( function () {
alert( "图片上传失败!" );
});
});
|
后端接收:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
@RequestMapping (value = "admin/upload" , method = RequestMethod.POST)
@ResponseBody
public String uploadFile( @RequestParam ( "file" ) MultipartFile file) {
try {
String filename = file.getOriginalFilename();
if (filename.endsWith( "jpg" ) || filename.endsWith( "png" ) || filename.endsWith( "gif" )) {
String prefix = filename.substring(filename.lastIndexOf( "." ));
String imgName = UUID.randomUUID().toString() + prefix;
String imgUri = writeToFileSystem(imgName, file.getBytes());
return imgUri;
}
} catch (Exception e) {
LOG.error( "uploadFile failed:" , e);
}
return null ;
}
|
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。
原文链接:http://www.cnblogs.com/dali-lyc/p/7351355.html