SpringMVC实现单个文件上传

    xiaoxiao2021-03-25  115

    /*单个文件上传Service代码片段 需要注意的是,后台controller接收的参数不能与对象的属性名同名,不然就会数据绑定错误,如果文件也是属于该对象中的属性,也不可以,因为这个file必须要用multipartFile对象进行接收,如果是多个multipartFile就使用多个对象进行接收参数*/ @Override public void addShop(Shops shop, MultipartFile photo, MultipartFile licensePhoto) throws IOException{ /*进行shop的持久化*/ shop.setApplyTime(DateUtil.format(new Date())); shop.setShopStatus(0); if(!photo.isEmpty() && photo.getSize()>0 && !licensePhoto.isEmpty() && licensePhoto.getSize()>0){ String sepa = File.separator; //通过springMVC获取session对象 ServletContext session = SysContent.getSession().getServletContext(); System.out.println(session); //项目根路径 String realPath = SysContent.getSession().getServletContext().getRealPath("/static/upload"); System.out.println(realPath); //得到上传时的文件名 String photoRename = SysContent.getFileRename(photo.getOriginalFilename()); String licensePhotoRename = SysContent.getFileRename(licensePhoto.getOriginalFilename()); //图片的完整路径 String photoRpn = realPath + sepa + photoRename; String licensePhotoRpn = realPath + sepa + licensePhotoRename; String savePhotoPath = photoRpn.substring(photoRpn.indexOf("static")); String saveLicensePath = licensePhotoRpn.substring(licensePhotoRpn.indexOf("static")); System.out.println("photoRpn: "+photoRpn+"licensePhotoRpn: "+licensePhotoRpn); //创建一个新的文件 File photoFile = new File(photoRpn); File licensePhotoFile = new File(licensePhotoRpn); FileUtils.copyInputStreamToFile(photo.getInputStream(), photoFile); FileUtils.copyInputStreamToFile(licensePhoto.getInputStream(), licensePhotoFile); //保存图片的url shop.setPhoto(savePhotoPath); shop.setLicensePhoto(saveLicensePath); //上传文件备份 SysContent.backUploadPics(photo, photoRename); SysContent.backUploadPics(licensePhoto, licensePhotoRename); } baseDao.save(shop); /*进行user的持久化处理*/ User user = new User(); user.setUserId(UUID.randomUUID().toString()); user.setCreateTime(shop.getApplyTime()); user.setParentId(shop.getShopId().toString()); user.setPhone(shop.getPhone()); user.setUserCaption(shop.getContactPerson()); String password = shop.getPhone().substring(5); user.setPassword(password); // List findByHql = baseDao.findByHql("from Role where id="+roleId); // if(findByHql != null){ // Role role = (Role) findByHql.get(0); // Set rSet = new HashSet(); // rSet.add(role); // user.setRoleId(rSet); // }else{ // System.out.println("注册失败"); // } baseDao.save(user); }
    转载请注明原文地址: https://ju.6miu.com/read-6052.html

    最新回复(0)