SSM图片或文件上传

这里的上传是上传到项目文件中。

(1)springmvc.xml文件中的配置

<!-- 资源上传 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
	<property name="defaultEncoding" value="utf-8"></property>
	<property name="maxUploadSize" value="5000000"></property>  
</bean>
(2)Jsp页面

数据只能同步提交,不能使用ajax异步提交。

form指明enctype="multipart/form-data"只能是同步提交。

<form action="userregist.action" method="post" enctype="multipart/form-data" id="itemForm">

(3)Jsp指明type为file

头像:<input type="file" name="pictureFile" class="pic"/> 
(4)用户注册Controller(包括头像上传)

在controller中要有图片或者文件接受的MultipartFile类型的参数,且名字与jsp页面提交的名字要一样;图片上传之后名字要变化,文件名字使用了生成随机名字的UUID,图片保存在本地硬盘中;把图片名字保存进数据库中。

@RequestMapping(value="userregist.action")
	public String toregist(TbUser u,MultipartFile pictureFile,HttpServletResponse response,HttpServletRequest request) throws Exception{
		//图片name
		String name = UUID.randomUUID().toString().replace("-", "");
		//后缀名jpg
		String ext = FilenameUtils.getExtension(pictureFile.getOriginalFilename());
		//实际的图片上传到upload硬盘上
		pictureFile.transferTo(new File("D:\\software\\eclipse-install\\myeclipse\\workspace\\bishe\\bishe4\\WebRoot\\upload\\"+name+"."+ext));		
		
		u.setImage(name+"."+ext);	
		u.setCb(5L);
		u.setGuancount(0L);
		u.setFancount(0L);
		tbuserservice.addUser(u);		
		return "redirect:/loginPage.action";
	}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值