首页 > 编程 > Java > 正文

SpringMVC框架实现上传图片的示例代码

2019-11-26 11:17:41
字体:
来源:转载
供稿:网友

一.创建图片虚拟目录

在上传图片之前,先要设置虚拟目录(以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>

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持武林网。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表