1,SSM由Maven管理
上传文件的jar包
依赖包如下:
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.3</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
2,编写Jsp文件
中间还要jstl的jar
<body>
<form action="upload.do" method="post" enctype="multipart/form-data">
<div>文件名称:<input type="text" name="filename" /></div>
<div>
<input type="file" name="file" />
<br>
<input type="submit" value="上传" />
<c:if test="${!empty(img)}">
<img width="100px" height="100px"
src="${pageContext.request.contextPath}${img}">
</c:if>
</div>
</form>
</body>
[注]src的路径问题
3,Controller控制器
小案例直接写controller
@RequestMapping("/toUpload.do")
public String toUpload(){
return "upload";
}
@RequestMapping("/upload.do")
public String fileupload(String filename,MultipartFile file,
HttpServletRequest req) throws IllegalStateException, IOException{
String file_path = "D:\\imgs\\";
//获取文件名
String oriName = file.getOriginalFilename();
//获取后缀
String extName = oriName.substring(oriName.lastIndexOf("."));
String fileName = "/files/"+filename+extName;
String uppath = req.getServletContext().getRealPath("/")+fileName;
//String uppath = req.getServletContext().getRealPath(fileName); //错误写法在这里花了折腾了一下
System.out.println(uppath);
file.transferTo(new File(uppath));
req.setAttribute("img",fileName);
return "upload";
}
req.getServletContext().getRealPath("/");
获取 服务器中当前WebRoot的物理路径
4,测试
打开浏览器测试数据对应路径,OK啦!!,,上传成功,显示在页面