步骤一、配置。在eclipse做如下修改:
1.双击Tomcat v7.0 Server at localhost
2.点击一下Modules
3.点击一下Add External Web Module...
4.填写你要的真实路径、虚拟路径
步骤二、测试。在Java工程src目录下加入文件imagePath.properties(文件名任意取)
1.imagePath.properties
#虚拟路径
imgPath=/image
#真实路径
imgRealPath=D:\\image
2.**Controller.java
@Controller
public class StudentController {
@Autowired
private StudentService studentService;
@RequestMapping(value = "/uploadPhoto")
public String uploadPhoto(HttpServletRequest request, Student student, MultipartFile pictureFile) throws Exception {
//获取properties的属性。
Properties prop =new Properties();
InputStream in=this.getClass().getClassLoader().getResourceAsStream("imgPath.properties");
prop.load(in);
// 使用UUID给图片重命名,并去掉四个“-”
String name = UUID.randomUUID().toString().replaceAll("-", "");
// 获取文件的扩展名
String ext = FilenameUtils.getExtension(pictureFile.getOriginalFilename());
//获取真实路径
String imgRealPath = prop.getProperty("imgRealPath").trim();
//获取虚拟路径
String imgPath = prop.getProperty("imgPath").trim();
// 根据真实路径保存重名命后的图片
pictureFile.transferTo(new File(imgRealPath +"/"+ name + "." + ext));
// 把图片存储路径保存到数据库
student.setPhoto(imgPath + "/" + name + "." + ext);
//更新学生信息
studentService.uploadPhoto(student);
// 重定向到查询所有用户的Controller,测试图片回显
return "redirect:/getAllStudents";
}
// 查询所有用户
@RequestMapping(value = "/getAllStudents")
public String getAllStudents(Model model) throws Exception {
List<Student> studentList = studentService.getAllStudents();
model.addAttribute("studentList", studentList);
return "success";
}
}
这段代码主要是告诉你真实路径、虚拟路径怎么获取
3.index.jsp
<form action="${pageContext.request.contextPath}/uploadPhoto" method="post" enctype="multipart/form-data">
sid:<input type="text" name="sid" /><br>
图片:<input type="file" name="pictureFile" /><br>
<input type="submit" value="提交">
</form>
更详细请参考:详细博文