项目中用到的 文件上传 添加到 数据库 保存路径
注意,上传功能,需要引入两个依赖
<!-- 文件上传的jar包 --><dependency><groupId>commons-io</groupId><artifactId>commons-io</artifactId><version>2.4</version></dependency><dependency><groupId>commons-fileupload</groupId><artifactId>commons-fileupload</artifactId><version>1.3.1</version></dependency>
在springmv.xml中配置上传文件解析器
<!-- 配置 文件上传--><bean class="org.springframework.web.multipart.commons.CommonsMultipartResolver" id="multipartResolver"><property name="defaultEncoding" value="utf-8"></property><property name="maxUploadSize" value="52424000"></property></bean>
首先就是 dao接口
UserMapper
//用户添加int addUser(User user);
UserMapper.xml
<!-- 插入用户信息 --><insert id="addUser" parameterType="com.lang.model.User">insert into t_user(userName,roleId,userImg,userAccount,userPassword,userTel,userWxid,userIdcard,userAddress,userDeleted,createTime,updateTime)values (#{
userName},#{
roleId},#{
userImg},#{
userAccount},#{
userPassword},#{
userTel},#{
userWxid},#{
userIdcard},#{
userAddress},0,Now(),Now())</insert>
UserService层
//用户添加String addUser(MultipartFile file, User user, ModelMap map) throws IOException;
UserServiceImpl层
@Transactional@Overridepublic String addUser(MultipartFile file, User user, ModelMap map) throws IOException {
userMapper.addUser(user);return "redirect:/userList.action";}
最后就是我们的 controller控制层
/*** 单个文件上传* @param* @return*/@RequestMapping(value = "/upload", method = RequestMethod.POST)public String upload( @RequestParam("userName") String name,@RequestParam("roleId") Integer roleId,@RequestParam("userAccount") String userAccount,@RequestParam("userPassword") String userPassword,@RequestParam("userTel") String userTel,@RequestParam("userWxid") String userWxid,@RequestParam("userIdcard") String userIdcard,@RequestParam("userAddress") String userAddress,@RequestParam("userImg") MultipartFile file,Model model,HttpServletResponse response, ModelMap map) throws IOException {
User user = new User();// 保存图片的路径,图片上传成功后,将路径保存到数据库String filePath = "E:\\apache-tomcat-9.0.37\\webapps\\upload\\";// 获取原始图片的扩展名String originalFilename = file.getOriginalFilename();// 生成文件新的名字String newFileName = originalFilename;// 封装上传文件位置的全路径File targetFile = new File(filePath, newFileName);file.transferTo(targetFile);// 封装数据user.setUserName(name);user.setRoleId(roleId);user.setUserImg(newFileName);user.setUserAccount(userAccount);user.setUserPassword(userPassword);user.setUserTel(userTel);user.setUserWxid(userWxid);user.setUserIdcard(userIdcard);user.setUserAddress(userAddress);user.setUserDeleted(0);user.setCreateTime(new Date());user.setUpdateTime(new Date());userService.addUser(file,user,map);return "redirect:userList.action";}
完结
有问题欢迎来搞!