SpringMVC上传

1.jsp代码
<form id="jvForm" action="upload.do" method="post" enctype="multipart/form-data">
		<table cellspacing="1" cellpadding="2" width="100%" border="0" class="pn-ftable">
			<tbody>
		
				<tr>
					<td width="20%"></td>
						<td width="80%" class="pn-fcontent">
					
						<input type="file" name="pic" />
					</td>
				</tr>
			
			</tbody>
			<tbody>
				<tr>
					<td class="pn-fbutton" colspan="2">
						<input type="submit" class="submit" value="提交"/>   <input type="reset" class="reset" value="重置"/>
					</td>
				</tr>
			</tbody>
		</table>
	</form>
</form>
2.配置springmvc-console.xml
<!-- 配置文件上传解析器 -->
	<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
		<property name="maxUploadSize" value="5242880"/>
	</bean>

3.java代码

@RequestMapping("/uploadPicCt.do")
	public void uploadPicCt(MultipartFile pic,HttpServletRequest request, HttpServletResponse response) throws IllegalStateException, IOException{
		if(pic != null && pic.getSize() > 0){
			// 1、文件改名
			String filename = pic.getOriginalFilename();
			String suffix = FilenameUtils.getExtension(filename);
			String uuid = UUID.randomUUID().toString().replace("-", "");
			String newName = uuid + "." + suffix;
			
			// 2、文件上传
			String realPath = request.getServletContext().getRealPath(""); // 项目的真实路径
			String imgUrl = "\\images\\" + newName; // 相对路径:用于jsp页面回显
			String path = realPath + imgUrl;
			pic.transferTo(new File(path));
			
			// 3、响应json串
			JSONObject jsonObject = new JSONObject();
			jsonObject.put("imgUrl", imgUrl);
			response.setContentType("application/json;charset=UTF-8");
			response.getWriter().write(jsonObject.toString());
		}
	}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值