創(chuàng)新互聯(lián)www.cdcxhl.cn八線動態(tài)BGP香港云服務(wù)器提供商,新人活動買多久送多久,劃算不套路!
這篇文章主要介紹如何實現(xiàn)Java后端SSM框架圖片上傳功能,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們一定要看完!
一、技術(shù)概述
(1)這個技術(shù)是做什么
這個技術(shù)是上傳圖片到服務(wù)器上,并且把地址存在數(shù)據(jù)庫中。前端調(diào)用的時候之間通過地址即可調(diào)用。
(2)學(xué)習(xí)該技術(shù)的原因
由于用戶在寫日記的時候也可以進(jìn)行圖片的上傳,同時還有用戶頭像的上傳。
二、技術(shù)詳述
以上傳用戶的頭像為例
(1)接口代碼
@RequestMapping(value = "user/profilePhoto", produces = "application/json; charset=utf-8") @ResponseBody public boolean imageUphold(@RequestParam("photo") MultipartFile file, Long phone) throws IOException { String filePath = ducumentBase;// 保存圖片的路徑 // String filePath = "/image";//保存圖片的路徑 // 獲取原始圖片的拓展名 String originalFilename = file.getOriginalFilename(); System.out.println("originalFilename: " + originalFilename); // 新的文件名字 String newFileName = UUID.randomUUID() + originalFilename; // 封裝上傳文件位置的全路徑 filePath += "/" + phone; System.out.println("filePath: " + filePath); File targetFile = new File(filePath, newFileName); if (!targetFile.exists()) { targetFile.mkdirs(); } // 把本地文件上傳到封裝上傳文件位置的全路徑 System.out.println("newFileName: " + newFileName); System.out.println("targetFile: " + targetFile.getName()); System.out.println("phone: " + phone); //System.out.println("afterPhone"); try { file.transferTo(targetFile); } catch (IllegalStateException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } String allPath=mappingPath + "/" + phone+ "/" + newFileName; System.out.println("存儲路徑為"+allPath); boolean result=onedayServiceImpl.updProfilePhoto(allPath, phone);//存在數(shù)據(jù)庫中,其中allPath的數(shù)據(jù)庫類型為varchar(1000) return result; }