ssm中的文件上传问题,Take it easy

在这里插入图片描述
🆗这个问题虽然代码不难,但是配置缺一不可

在SpringMVC配置下的文件上传

对页面的要求:
	form表单的属性method:post请求(get请求没有请求体)
	form表单的属性enctype:默认值是application/x-www-form-urlencoded
	将它设置为multipart/form-data
	使用<input type="file">选择文件

后台如何接收数据

步骤
1.导入文件上传的依赖	包名:
`1.commons-fileupload     
2.commons-io`	

在springmvc.xml文件中配置上传的解析器

<!--文件上传必备的bean id不可以改变-->
	<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
	<!--设置最大的上传的文件大小 : 10M
	这个必须必须要设置!!!!!!上回我就是因为忘了设置文件的大小,
	找不出问题在哪里改这改那差点没推掉整个项目.....血的教训
	-->
	<property name="maxUploadSize" value="10485760"/>
	<!--这里设置的文件大小可以按照你想要的大小设置 
	 众所周知1KB=1024B,这里我想要限制10M那就是10*1M=10*1024KB=10*1024*1024B=10485760B
	这里的单位是B,那么结果就是10485760-->
	

如果用的是maven项目导入依赖

	<dependency>
  	    <groupId>commons-fileupload</groupId>
    	<artifactId>commons-fileupload</artifactId>
   	<version>1.3.1</version>
   	//值得注意的是,commons-fileupload包已经含有了conmons-io包,
   	//但是如果你想更改它的版本,那么再导入一个commons-io包就可以覆盖了
	</dependency>

🆗接下来是Controller的代码

@RequestMapping("/addUser.action")
public User queryUserByCondition(User user,MultipartFile photo){
	if(photo==null){
		throw new UserException("请选择图片");
	}else{
		//保存文件
		String savePath="D:\\upload";
		//File类
		File pathFile=new File(savePath);
		if(!pathFile.exists()){
				//创建文件夹
				pathFile.mkdirs();
		}
		//文件名的取名:时间戳/UUID
		String uploadFileName=photo.getOriginalFilename();
		String suffix=uploadFileName.subString(uploadFileName.lastIndexOf(","));
		String saveFilename=UUID.randomUUID().toString().replace("-","").toUpperCase()+suffix;
		//保存
		photo.transferTo(new File(savePath,saveFilename));
		//给user对象的photoPath赋值
		user.serPhotoPath(saveFilename);
		//调用业务层,保存用户
		userService.saveUser(user);
		model.addAttribute("msg","保存成功");
		return "msg";//页面
	}
}

在这里插入图片描述

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值