SpringMVC框架实现上传图片的示例代码
一.创建图片虚拟目录
在上传图片之前,先要设置虚拟目录(以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类型解析器。
<!--文件上传--> <bean id ="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="maxUploadSize"> <value>5242880</value> </property> </bean>
2.添加依赖
<!-- 文件上传 --> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.1</version> </dependency>
3. 在Login1.jsp页面form中提交enctype="multipart/form-data"的数据
<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
@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
<%@ 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>
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。
相关文章
java开发hutool HttpUtil网络请求工具使用demo
这篇文章主要为大家介绍了hutool之HttpUtil网络请求工具使用示例详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪2023-07-07SpringBoot+Quartz实现定时任务的代码模版分享
quartz 是一款开源且丰富特性的Java 任务调度库,用于实现任务调度和定时任务,本文主要和大家分享一个SpringBoot整合Quartz实现定时任务的代码模版,需要的可以参考一下2023-06-06一篇文章带你了解jdk1.8新特性--为什么使用lambda表达式
Lambda是一个匿名函数,我们可以把Lambda表达式理解为是一段可以传递的代码,本篇文章就带你了解,希望能给你带来帮助2021-08-08
最新评论