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進行儲存,但覺得這樣不好,遂改為儲存圖片地址的方式進行上傳。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。