這篇文章主要介紹如何實現Java后端SSM框架圖片上傳功能,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們一定要看完!
一、技術概述
(1)這個技術是做什么
這個技術是上傳圖片到服務器上,并且把地址存在數據庫中。前端調用的時候之間通過地址即可調用。
(2)學習該技術的原因
由于用戶在寫日記的時候也可以進行圖片的上傳,同時還有用戶頭像的上傳。
二、技術詳述
以上傳用戶的頭像為例
(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);//存在數據庫中,其中allPath的數據庫類型為varchar(1000) return result; }
其中的ducumentBase以及mappingPath
@Value("${ducument.base}")
private String ducumentBase;
@Value("${mapping.path}")
private String mappingPath;
為全局變量
配置文件
ducument.base = D://oneday_uphold
mapping.path = /images
(2)解釋
用MultipartFile來接收圖片的二進制碼,然后使用路徑+圖片名+隨機數保存圖片。
(3)測試jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>image/uphold</title> </head> <body> <form action="user/profilePhoto" method="post" enctype="multipart/form-data"> 圖片:<input type="file" name="photo"> 電話:<input type="text" name="phone" value="13225942005"> <input type="submit" value="提交"> </form> </body> </html>
(4)顯示圖片
<img id="images" alt="頭像" src="/mappingPath/路徑">
三、技術使用中遇到的問題和解決過程
(1)無法保存:
查看是否已進行服務器的設置,以Eclipse為例
Servers->Modules->Add External Web Modules 進行路徑的設置
(2)無法訪問接口:
查看是否使用表單形式訪問:method="post" enctype="multipart/form-data"
同時上傳的名字是否與接口相對應
本來進行圖片的上傳的時候考慮過直接上傳二進制到數據庫用blob進行保存,但覺得這樣不好,遂改為保存圖片地址的方式進行上傳。
以上是如何實現Java后端SSM框架圖片上傳功能的所有內容,感謝各位的閱讀!希望分享的內容對大家有幫助,更多相關知識,歡迎關注億速云行業資訊頻道!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。