SSM实现简单文件上传

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啦!!,,上传成功,显示在页面

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值