一.创建图片虚拟目录
在上传图片之前,先要设置虚拟目录(以idea为例)
- 打开工具栏的运行配置edit configurations
- 添加物理目录和并设置虚拟目录路径
添加img图片在img文件夹内
测试访问:http://localhost:8080/img/img.jpg
二.springmvc上传头像
1.springmvc对多部件类型的解析
上传图片springmvc.xml配置
在页面form中提交enctype="multipart/form-data"的数据时,需要springmvc对multipart类型的数据进行解析。在springmvc.xml中配置multipart类型解析器。
1
2
3
4
5
6
|
<!--文件上传-->
<bean id = "multipartresolver" class = "org.springframework.web.multipart.commons.commonsmultipartresolver" >
<property name= "maxuploadsize" >
<value> 5242880 </value>
</property>
</bean>
|
2.添加依赖
1
2
3
4
5
6
|
<!-- 文件上传 -->
<dependency>
<groupid>commons-fileupload</groupid>
<artifactid>commons-fileupload</artifactid>
<version> 1.3 . 1 </version>
</dependency>
|
3. 在login1.jsp页面form中提交enctype="multipart/form-data"的数据
1
2
3
4
5
6
7
8
9
|
<form action= "/usercontroller/insertuser" method= "post" enctype= "multipart/form-data" >
<input type= "text" required= "required" placeholder= "用户名" name= "username" >
<input type= "password" required= "required" placeholder= "密码" name= "password" >
<input type= "file" name = "imgfile" >
<div id= "bt" >
<input class = "but" type= "submit" value= "注册" >
<a href= "register.jsp" rel= "external nofollow" ><input class = "but" type= "button" value= "返回登录" ></a>
</div>
</form>
|
4.处理请求usercontroller.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
@requestmapping ( "insertuser" )
public string insertuser (httpservletrequest request, user user, multipartfile imgfile) throws ioexception {
//获取文件原始名称
string originalfilename = imgfile.getoriginalfilename();
//上传图片
if (imgfile!= null && originalfilename!= null && originalfilename.length()> 0 ){
//存储图片的物理路径
string pic_path = "/home/ubuntu/idea/ssm/img/" ;
//新的图片名称
string newfilename = uuid.randomuuid() + originalfilename.substring(originalfilename.lastindexof( "." ));
//新图片
file newfile = new file(pic_path+newfilename);
//将内存中的数据写入磁盘
imgfile.transferto(newfile);
userservice.insertuser(user,newfilename);
httpsession session = request.getsession();
session.setattribute( "imgurl" , newfilename);
}
return "item/success" ;
}
|
上传成功
成功跳转页面success.jsp
1
2
3
4
5
6
7
8
9
10
11
|
<%@ page contenttype= "text/html;charset=utf-8" language= "java" %>
<html>
<head>
<title>成功</title>
</head>
<body>
<h1>成功页面</h1>
<img style= "width: 150px; height: 200px"
src= "http://localhost:8080/img/<%=session.getattribute(" imgurl ")%>" >
</body>
</html>
|
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。
原文链接:http://www.jianshu.com/p/24bb6a4be071?utm_source=tuicool&utm_medium=referral