SSM框架实现图片上传到工程目录下的upload文件夹与图片回显

有任何问题加群讨论

群号:733899823

加群时请备注CSDN~

还可以关注我的个人微信公众号,免费领取Java全栈学习资料呦~

一、工程目录如下:

二、上传测试页面-register.jsp:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>上传图片测试</title>
</head>
<body>

	<form action="${pageContext.request.contextPath}/addUser" method="post" enctype="multipart/form-data">
		用户名:<input type = "text"  name = "username" /><br>
		图片: <input type="file"     name = "pictureFile" /><br>
			<input type = "submit" value = "提交">
	</form>

</body>
</html>

三、上传与回显测试的Controller-UserController.java:

package com.xiao.controller;

import java.io.File;
import java.util.List;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import com.xiao.pojo.User;
import com.xiao.service.UserService;

@Controller
public class UserController {
	
	@Autowired
	private UserService userService;
	
	
	@RequestMapping(value = "/addUser")
	public String addUser(HttpServletRequest request ,User user,MultipartFile pictureFile) throws Exception{
		
		//使用UUID给图片重命名,并去掉四个“-”
		String name = UUID.randomUUID().toString().replaceAll("-", "");
		//获取文件的扩展名
		String ext = FilenameUtils.getExtension(pictureFile.getOriginalFilename());
		//设置图片上传路径
		String url = request.getSession().getServletContext().getRealPath("/upload");
		System.out.println(url);
		//以绝对路径保存重名命后的图片
		pictureFile.transferTo(new File(url+"/"+name + "." + ext));
		//把图片存储路径保存到数据库
		user.setImageURL("upload/"+name + "." + ext);
		
		userService.addUser(user);
		//重定向到查询所有用户的Controller,测试图片回显
		return "redirect:/getAll";
		
	}
	//查询所有用户
	@RequestMapping(value = "/getAll")
	public String getAll(Model model) throws Exception{
		List<User> userList = userService.getAll();
		model.addAttribute("userList",userList);
		return "userList";
	}

}

以上url的打印地址为:C:\Users\Administrator\Desktop\Test\Test\src\main\webapp\upload,路径最后少了个斜杠,所以,我在pictureFile.transferTo(new File(url+"/"+name + "." + ext));  这句代码中拼接了一个“/”,这样文件才会上传到upload文件夹中

保存到数据库的地址为:upload/UUID生成的文件名.jpg

另外还得注意一点:图片提交input输入框的name属性值要与Controller中MultipartFile接口所声明的形参名一致,不然需要用@RequestParam注解绑定

四、由于我的前端控制器配置的是拦截所有请求,所以要在在springmvc.xml中放行静态资源:

<mvc:resources location="/upload/" mapping="/upload/**"/>

五、在springmvc.xml中还需配置文件上传解析器:

<!-- 定义文件上传解析器 -->
	<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
		<!-- 设定默认编码 -->
		<property name="defaultEncoding" value="UTF-8"></property>
		<!-- 设定文件上传的最大值5MB,5*1024*1024 -->
		<property name="maxUploadSize" value="5242880"></property>
	</bean>

六、回显测试页面-userList.jsp:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>测试图片回显</title>
</head>
<body>
<c:forEach items="${userList}" var="userList" >
	${userList.username}<br><br><br><br>
	<!--拼接图片回显的的URL-->
	<img  src="http://localhost:8080/${userList.imageURL}" 
	width="500" height="500"><br><br><br><br>
</c:forEach>
</body>
</html>

七、效果演示:

 

数据库表:

 

说明

如果上述方法获取的路径不对,可以试试如下方法:

 File directory = new File("");// 参数为空
 String workspacePath = directory.getCanonicalPath(); //获取工作空间的绝对路径
 System.out.println(workspacePath);
 String uploadDicPath = "\\src\\main\\webapp\\upload\\"; //手动添加上传文件夹的路径
 String uploadPath = workspacePath + uploadDicPath; //最终图片上传的路径
 System.out.println(uploadPath);

 

©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页