1. 程式人生 > >SpringMVC實現單個檔案上傳

SpringMVC實現單個檔案上傳

/*單個檔案上傳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); }