Java后端SSM框架圖片上傳功能實現方法解析
一、技術概述
(1)這個技術是做什么
這個技術是上傳圖片到服務器上,并且把地址存在數據庫中。前端調用的時候之間通過地址即可調用。
(2)學習該技術的原因
由于用戶在寫日記的時候也可以進行圖片的上傳,同時還有用戶頭像的上傳。
二、技術詳述
以上傳用戶的頭像為例
(1)接口代碼
@RequestMapping(value = 'user/profilePhoto', produces = 'application/json; charset=utf-8')@ResponseBodypublic 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 blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.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_upholdmapping.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 alt='頭像' src='http://m.lshqa.cn/mappingPath/路徑'>
三、技術使用中遇到的問題和解決過程
(1)無法保存:
查看是否已進行服務器的設置,以Eclipse為例
Servers->Modules->Add External Web Modules 進行路徑的設置
(2)無法訪問接口:
查看是否使用表單形式訪問:method='post' enctype='multipart/form-data'
同時上傳的名字是否與接口相對應
四、總結
本來進行圖片的上傳的時候考慮過直接上傳二進制到數據庫用blob進行保存,但覺得這樣不好,遂改為保存圖片地址的方式進行上傳。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持好吧啦網。
相關文章: