图片管理应用
文章目錄
- 一、簡(jiǎn)介
- 二、父項(xiàng)目
- 三、圖片管理服務(wù)的數(shù)據(jù)庫(kù)設(shè)計(jì)
- 四、定義module : img_pojo
- 五、定義module : img_mapper
- 六、定義module : img_service_api
- 七、module : img_service_provider
- 八、 定義module : imp_service_consumer
一、簡(jiǎn)介
內(nèi)容:
實(shí)現(xiàn)一個(gè)圖片管理應(yīng)用。可以上傳圖片,查看圖片,刪除圖片,下載圖片。
技術(shù):
SpringBoot:開發(fā)平臺(tái)
Dubbo:遠(yuǎn)程服務(wù)調(diào)用技術(shù)
MyBatis:數(shù)據(jù)庫(kù)訪問(wèn)
MySQL:數(shù)據(jù)庫(kù)
Zookeeper:Dubbo的注冊(cè)中心
FastDFS:集中管理所有上傳的圖片
Nginx:為FastDFS中的Storage服務(wù)器,提供一個(gè)虛擬主機(jī),就是可以在線使用瀏覽器查看Storage內(nèi)的圖片。
實(shí)現(xiàn):
實(shí)體 - 定義module : img_pojo
module中定義需要的實(shí)體類型
數(shù)據(jù)訪問(wèn) - 定義module : img_mapper
module中定義需要的數(shù)據(jù)訪問(wèn)接口和SQL映射文件。
服務(wù)標(biāo)準(zhǔn) - 定義module : img_service_api
module中定義dubbo遠(yuǎn)程訪問(wèn)是的服務(wù)標(biāo)準(zhǔn)接口。只定義標(biāo)準(zhǔn)接口。
服務(wù)提供者 - 定義module : img_service_provider
module中實(shí)現(xiàn)img_service_api中的服務(wù)接口,并發(fā)布服務(wù)。在zk中發(fā)布服務(wù)信息。
服務(wù)消費(fèi)者 - 定義module : imp_service_consumer
module中使用img_service_api中的接口,遠(yuǎn)程調(diào)用服務(wù)提供者給予的實(shí)現(xiàn)。
提供客戶視圖(UI)
提供圖片上傳|下載。 圖片上傳|下載不適合使用dubbo處理。
二、父項(xiàng)目
pom.xml
<dependencyManagement><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-dependencies</artifactId><version>2.2.5.RELEASE</version><type>pom</type><scope>import</scope></dependency><dependency><groupId>org.apache.dubbo</groupId><artifactId>dubbo-spring-boot-starter</artifactId><version>2.7.5</version></dependency><!-- 訪問(wèn)zookeeper的Java客戶端應(yīng)用 --><dependency><groupId>org.apache.curator</groupId><artifactId>curator-recipes</artifactId><version>4.3.0</version></dependency><!-- 訪問(wèn)zookeeper的Java客戶端應(yīng)用 --><dependency><groupId>org.apache.curator</groupId><artifactId>curator-framework</artifactId><version>4.3.0</version></dependency><!-- 分頁(yè) --><dependency><groupId>com.github.pagehelper</groupId><artifactId>pagehelper-spring-boot-starter</artifactId><version>1.2.13</version></dependency><dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>2.1.1</version></dependency><dependency><groupId>cn.bestwu</groupId><artifactId>fastdfs-client-java</artifactId><version>1.27</version></dependency><dependency><groupId>org.apache.commons</groupId><artifactId>commons-lang3</artifactId><version>3.9</version></dependency></dependencies></dependencyManagement>三、圖片管理服務(wù)的數(shù)據(jù)庫(kù)設(shè)計(jì)
-- 創(chuàng)建圖片表格 create table img_manage(id bigint not null auto_increment comment '主鍵',url varchar(255) default '' comment '訪問(wèn)這個(gè)圖片的HTTP地址',group_name varchar(64) default 'group1' comment 'FastDFS中的卷名',remote_file_name varchar(255) default '' comment 'FastDFS中的文件名,如:M00/00/00/abc.jpg',origin_file_name varchar(255) default '' comment '上傳的圖片的原始名稱',upload_time date not null comment '上傳圖片的時(shí)間',primary key (id) ) comment '保存上傳到FastDFS中的圖片信息表';四、定義module : img_pojo
public class Image implements Serializable {private Long id;private String groupName;private String remoteFileName;private String originFileName;private Date uploadTime;public String getUrl(){return groupName + "/" + remoteFileName;}public void setUrl(String url){// url屬性為推導(dǎo)屬性。url的值,是由groupName和remoteFileName組合得到。}//其他正常五、定義module : img_mapper
pom.xml
<dependencies><dependency><groupId>com.bjsxt</groupId><artifactId>img_pojo</artifactId><version>1.0-SNAPSHOT</version></dependency><dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId></dependency></dependencies>com.bjsxt.img.mapper
package com.bjsxt.img.mapper;import com.bjsxt.img.pojo.Image;import java.util.List;/*** 圖片數(shù)據(jù)訪問(wèn)接口。連接數(shù)據(jù)庫(kù)MySQL實(shí)現(xiàn)數(shù)據(jù)CRUD操作。*/ public interface ImageMapper {// 新增數(shù)據(jù)int insert(Image image);// 刪除數(shù)據(jù)int deleteByPK(Long id);// 主鍵查詢Image selectById(Long id);// 全數(shù)據(jù)查詢List<Image> select(); }ImageMapper.xml
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.bjsxt.img.mapper.ImageMapper"><resultMap id="ImageMap" type="com.bjsxt.img.pojo.Image"><id property="id" column="id" /><result property="groupName" column="group_name" /><result property="remoteFileName" column="remote_file_name" /><result property="originFileName" column="origin_file_name" /><result property="uploadTime" column="upload_time" /><result property="url" column="url" /></resultMap><insert id="insert" keyProperty="id" useGeneratedKeys="true" keyColumn="id">insert into img_manage(id, url, group_name, remote_file_name, origin_file_name, upload_time)values(DEFAULT, #{url}, #{groupName}, #{remoteFileName}, #{originFileName}, #{uploadTime})</insert><delete id="deleteByPK">delete from img_managewhere id = #{id}</delete><select id="selectById" resultMap="ImageMap">select id, url, group_name, remote_file_name, origin_file_name, upload_timefrom img_managewhere id = #{id}</select><select id="select" resultMap="ImageMap">select id, url, group_name, remote_file_name, origin_file_name, upload_timefrom img_manage</select></mapper>application.yml
mybatis: # sql映射文件mapper-locations: classpath:mybatis/mapper/*.xmlspring:datasource:driver-class-name: com.mysql.cj.jdbc.Driverurl: jdbc:mysql://localhost:3306/test?serverTimezone=GMT%2B8username: rootpassword: 1234六、定義module : img_service_api
pom.xml
<dependencies><dependency><groupId>com.bjsxt</groupId><artifactId>img_pojo</artifactId><version>1.0-SNAPSHOT</version></dependency></dependencies>com.bjsxt.img.serviceapi
package com.bjsxt.img.serviceapi;import com.bjsxt.img.pojo.Image;import java.util.Map;/*** 圖片服務(wù)標(biāo)準(zhǔn)接口。* dubbo的Provider需要實(shí)現(xiàn)這個(gè)接口提供服務(wù)* dubbo的Consumer需要使用這個(gè)接口調(diào)用服務(wù)*/ public interface ImageServiceAPI {// 新增圖片int save(Image image);// 刪除圖片int remove(Long id);// 查看圖片詳情Image getById(Long id);// 分頁(yè)查看圖片信息,使用PageHelper實(shí)現(xiàn)分頁(yè)。// 返回的結(jié)果是: {rows=[{圖片對(duì)象}], total=總計(jì)圖片數(shù)量, currentPage=當(dāng)前頁(yè)碼, pages=總計(jì)頁(yè)數(shù), size=每頁(yè)行數(shù)}Map<String, Object> getImages(int page, int rows); }七、module : img_service_provider
pom.xml
<dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter</artifactId></dependency><dependency><groupId>org.apache.dubbo</groupId><artifactId>dubbo-spring-boot-starter</artifactId></dependency><dependency><groupId>org.apache.curator</groupId><artifactId>curator-recipes</artifactId></dependency><dependency><groupId>org.apache.curator</groupId><artifactId>curator-framework</artifactId></dependency><dependency><groupId>com.github.pagehelper</groupId><artifactId>pagehelper-spring-boot-starter</artifactId></dependency><dependency><groupId>com.bjsxt</groupId><artifactId>img_service_api</artifactId><version>1.0-SNAPSHOT</version></dependency><dependency><groupId>com.bjsxt</groupId><artifactId>img_mapper</artifactId><version>1.0-SNAPSHOT</version></dependency></dependencies>com.bjsxt.img.service.impl
package com.bjsxt.img.service.impl;import com.bjsxt.img.mapper.ImageMapper; import com.bjsxt.img.pojo.Image; import com.bjsxt.img.serviceapi.ImageServiceAPI; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import org.apache.dubbo.config.annotation.Service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.transaction.annotation.Transactional;import java.util.HashMap; import java.util.List; import java.util.Map;/*** 服務(wù)提供者, 實(shí)現(xiàn)服務(wù)標(biāo)準(zhǔn)。* 這個(gè)Service注解是dubbo的Service注解* @Transactional事務(wù)管理*/ @Service public class ImageServiceImpl implements ImageServiceAPI {// 注入Mapper對(duì)象@Autowiredprivate ImageMapper imageMapper;/*** 新增圖片到數(shù)據(jù)庫(kù)* @param image 要新增的數(shù)據(jù)對(duì)象* @return*/@Override@Transactionalpublic int save(Image image) {return imageMapper.insert(image);}/*** 刪除數(shù)據(jù)* @param id 要?jiǎng)h除的數(shù)據(jù)主鍵* @return*/@Override@Transactionalpublic int remove(Long id) {return imageMapper.deleteByPK(id);}/*** 主鍵查詢 * 注意:查詢是只讀的,不考慮 @Transactional* @param id 要查詢的數(shù)據(jù)的主鍵* @return*/@Overridepublic Image getById(Long id) {return imageMapper.selectById(id);}/*** 分頁(yè)查詢* @param page 第幾頁(yè)* @param rows 多少行* @return*/@Overridepublic Map<String, Object> getImages(int page, int rows) {// 使用分頁(yè)查詢PageHelper.startPage(page, rows);// 分頁(yè)查詢, 返回的結(jié)果是PageHelper封裝的List的實(shí)現(xiàn)類型PageList<Image> list = imageMapper.select();// 使用PageInfo輔助工具對(duì)象,實(shí)現(xiàn)分頁(yè)數(shù)據(jù)的獲取PageInfo<Image> info = new PageInfo<>(list);// 創(chuàng)建返回結(jié)果Map<String, Object> result = new HashMap<>();result.put("total", info.getTotal()); // 總計(jì)數(shù)據(jù)行數(shù)result.put("rows", list); // 當(dāng)前頁(yè)面的數(shù)據(jù)集合result.put("currentPage", page); // 當(dāng)前是第幾頁(yè)result.put("pages", info.getPages()); // 總計(jì)多少頁(yè)result.put("size", rows); // 每頁(yè)顯示多少行。return result; } }啟動(dòng)類
com.bjsxt.img
application.yml
spring:profiles:active: db dubbo:application: # dubbo應(yīng)用必須提供一個(gè)唯一的命名。同名的dubbo應(yīng)用自動(dòng)組成集群。name: img_manage_providerprotocol:name: dubboport: 20880registry:address: zookeeper://192.168.14.129:2181config-center:timeout: 10000 server:port: 8081 pagehelper:helper-dialect: mysql啟動(dòng)zookeeper,啟動(dòng)ImageProviderApp
八、 定義module : imp_service_consumer
pom.xml
<dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-thymeleaf</artifactId></dependency><dependency><groupId>org.apache.dubbo</groupId><artifactId>dubbo-spring-boot-starter</artifactId></dependency><dependency><groupId>org.apache.curator</groupId><artifactId>curator-recipes</artifactId></dependency><dependency><groupId>org.apache.curator</groupId><artifactId>curator-framework</artifactId></dependency><dependency><groupId>cn.bestwu</groupId><artifactId>fastdfs-client-java</artifactId></dependency><dependency><groupId>org.apache.commons</groupId><artifactId>commons-lang3</artifactId></dependency><dependency><groupId>com.bjsxt</groupId><artifactId>img_service_api</artifactId><version>1.0-SNAPSHOT</version></dependency></dependencies>application.yml
# FastDFS客戶端配置 fdfs:connect-timeout: 10network-timeout: 30charset: UTF-8http:tracker_http_port: 8080tracker_server: 192.168.14.129:22122dubbo:application:name: img_manage_consumerregistry:address: zookeeper://192.168.14.129:2181server:port: 80FastDFSUtils.java
package com.bjsxt.img.utils;import org.csource.common.NameValuePair; import org.csource.fastdfs.*;import java.util.Properties;public class FastDFSUtils {// 通過(guò)static初始化代碼塊,讀取配置文件,初始化客戶端連接對(duì)象。// 客戶端連接對(duì)象,用于實(shí)現(xiàn)文件讀寫操作使用。private StorageClient storageClient;// 默認(rèn)構(gòu)造public FastDFSUtils() {// 提供默認(rèn)配置Properties properties = new Properties();properties.setProperty("fastdfs.connect_timeout_in_seconds", "5");properties.setProperty("fastdfs.network_timeout_in_seconds", "30");properties.setProperty("fastdfs.charset", "UTF-8");properties.setProperty("fastdfs.http_tracker_http_port", "8080");properties.setProperty("fastdfs.tracker_servers", "localhost:22122");init(properties);}public FastDFSUtils(Properties properties) {init(properties);}public void init(Properties properties){try {// 讀取配置文件,借助SpringBoot實(shí)現(xiàn)配置ClientGlobal.initByProperties(properties);// 創(chuàng)建Tracker客戶端對(duì)象TrackerClient trackerClient = new TrackerClient();// 創(chuàng)建Tracker服務(wù)器對(duì)象TrackerServer trackerServer = trackerClient.getConnection();// 創(chuàng)建Storage服務(wù)器對(duì)象StorageServer storageServer = trackerClient.getStoreStorage(trackerServer);// 創(chuàng)建Storage客戶端對(duì)象storageClient = new StorageClient(trackerServer, storageServer);}catch(Exception e){e.printStackTrace();// 初始化代碼塊出錯(cuò),一定要拋出錯(cuò)誤,停止虛擬機(jī)。throw new ExceptionInInitializerError(e);}}/*** 文件刪除,FastDFS會(huì)自動(dòng)刪除這個(gè)文件對(duì)應(yīng)的metaData。就是文件名-m這個(gè)文件。*/public boolean deleteFile(String groupName, String fileName){try{// storageClient.delete_file(String groupName, String fileName);// groupName - 要?jiǎng)h除的文件的卷名,就是保存文件的storage服務(wù)配置中的groupName// fileName - 要?jiǎng)h除的文件的文件名,包含路徑地址。格式:M00/目錄/目錄/文件名.后綴名// M00代表保存文件的目錄, store_path0 。 目錄/目錄 - 保存文件的具體位置。int result = storageClient.delete_file(groupName, fileName);// 返回結(jié)果為0,代表刪除成功,其他是刪除失敗。return result == 0;}catch(Exception e){e.printStackTrace();return false;}}/*** 文件下載* @param metaDatas - 傳入一個(gè)數(shù)組,用于保存下載文件的擴(kuò)展信息。如果傳入null,則不需要文件擴(kuò)展信息。* 如果傳入的數(shù)組不是null,則需要文件的擴(kuò)展信息。* @return 下載的文件內(nèi)容*/public byte[] downloadFile(String groupName, String fileName, NameValuePair[] metaDatas){try{/** byte[] storageClient.download_file(String groupName, String fileName);* groupName - 卷名 | 組名* fileName - 文件名,是文件保存在fdfs中的目錄和文件名。*/byte[] datas = storageClient.download_file(groupName, fileName);// 要下載的文件的擴(kuò)展信息。if(metaDatas != null) {NameValuePair[] tmp = storageClient.get_metadata(groupName, fileName);// 把查詢到的文件擴(kuò)展信息。保存到傳入的數(shù)組中。for(int i = 0; i < tmp.length; i++){metaDatas[i] = tmp[i];}}// 返回下載的文件內(nèi)容return datas;}catch(Exception e){e.printStackTrace();return null; // 下載失敗,返回null}}/*** 使用StorageClient對(duì)象,實(shí)現(xiàn)文件的上傳。*/public String[] uploadFile(byte[] datas, String fileName, String authName){try{// 文件上傳// 獲取文件的擴(kuò)展名String extName = fileName.substring(fileName.lastIndexOf(".") + 1);// 創(chuàng)建文件擴(kuò)展信息。擴(kuò)展信息包括文件的原始名稱,文件的大小,文件的上傳者姓名NameValuePair[] metaDatas = new NameValuePair[3];metaDatas[0] = new NameValuePair("fileName", fileName);metaDatas[1] = new NameValuePair("fileSize", datas.length+"");metaDatas[2] = new NameValuePair("auth", authName);/** String[] storageClient.upload_file(byte[] datas, String extName, NameValuePair[] metaDatas)* datas - 要上傳的文件的內(nèi)容* extName - 上傳的文件的擴(kuò)展名* metaDatas - 上傳的文件的擴(kuò)展信息是什么。 如:文件的原始名稱、文件的容量大小、文件的上傳者等。*/String[] result = storageClient.upload_file(datas, extName, metaDatas);// 上傳成功,無(wú)異常。返回字符串?dāng)?shù)組。// 字符串?dāng)?shù)組長(zhǎng)度為2。 0下標(biāo)位置是 卷名|組名。 1下標(biāo)位置是 文件名(目錄/文件)// fdfs為了解決上傳的文件原始名稱沖突內(nèi)容不沖突而覆蓋的問(wèn)題,存儲(chǔ)文件的時(shí)候,會(huì)提供一個(gè)uuid文件名稱。return result;}catch(Exception e){e.printStackTrace();return null; // 異常發(fā)生,返回null。代表上傳失敗。}} }FastDFS客戶端工具類型需要使用的自動(dòng)裝配對(duì)象,用來(lái)創(chuàng)建工具類型的對(duì)象。
spring容器管理創(chuàng)建的工具類型的對(duì)象
服務(wù)接口ImageService
package com.bjsxt.img.service;import com.bjsxt.img.pojo.Image;import java.util.Map;/*** 本地的服務(wù)接口*/ public interface ImageService {// 保存圖片, 新增int save(Image image);// 刪除圖片int remove(Long id);// 主鍵查詢圖片詳情Image getById(Long id);// 分頁(yè)查詢圖片信息Map<String, Object> getImages(int page, int rows); }服務(wù)接口ImageService的實(shí)現(xiàn)類
ImageServiceImpl
ImageController
package com.bjsxt.img.contoller;import com.bjsxt.img.pojo.Image; import com.bjsxt.img.service.ImageService; import com.bjsxt.img.utils.FastDFSUtils; import org.csource.common.NameValuePair; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartFile;import javax.servlet.http.HttpServletResponse; import java.awt.im.InputContext; import java.io.InputStream; import java.net.URLEncoder; import java.util.Date; import java.util.HashMap; import java.util.Map;/*** 圖片服務(wù)的控制器。與客戶直接交互。*/ @Controller public class ImageController {@Autowiredprivate ImageService imageService;@Autowiredprivate FastDFSUtils utils;/*** 首頁(yè)面跳轉(zhuǎn)方法。 就是分頁(yè)查詢圖片服務(wù)中所有可以管理的圖片信息。* @param page 查詢第幾頁(yè), 默認(rèn)第一頁(yè)* @param rows 查詢多少航,默認(rèn)查五行* @param model 傳遞查詢結(jié)果到視圖。* {rows:[], total:, currentPage: pages, size}* @return 視圖邏輯*/@GetMapping(value = {"/", "/index"})public String toIndex(@RequestParam(value = "page", defaultValue = "1") int page,@RequestParam(value = "rows", defaultValue = "5") int rows,Model model){// 調(diào)用服務(wù)邏輯,分頁(yè)查詢Map<String, Object> result = this.imageService.getImages(page, rows);// 查詢結(jié)果使用請(qǐng)求作用域傳遞給頁(yè)面。model.addAttribute("datas", result);return "index";} }index.html
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.w3.org/1999/xhtml"> <head><meta charset="UTF-8"><title>圖片管理-分頁(yè)查看</title> </head> <body><div style="width: 800px; margin: auto; padding-top:50px; text-align: center"><a href="/toUpload">上傳圖片</a></div><div style="width: 800px; margin: auto; padding-top:50px; text-align: center"><table border="1"><caption>圖片列表</caption><thead><tr><th>序號(hào)</th><th>卷名</th><th>文件原始名</th><th>上傳時(shí)間</th><th>預(yù)覽</th><th>操作</th></tr></thead><tbody><tr th:each="imageObj : ${datas.rows}"><th th:text="${imageObj.id}"></th><th th:text="${imageObj.groupName}"></th><th th:text="${imageObj.originFileName}"></th><th th:text="${#dates.format(imageObj.uploadTime, 'yyyy-MM-dd HH:mm:ss')}"></th><th><img style="height: 50px; padding:5px" th:src="@{'http://192.168.14.129:8888/' + ${imageObj.url}}"></th><th><a target="_blank" th:href="@{/download(id=${imageObj.id})}">下載</a><a th:href="@{/remove(id=${imageObj.id})}">刪除</a></th></tr><tr><th colspan="6"><span th:text="${#strings.concat('總計(jì)', datas.total, '條')}"></span> <a th:if="${datas.currentPage} != 1" th:href="@{/index(page=${datas.currentPage-1},rows=${datas.size})}">上一頁(yè)</a><a th:if="${datas.currentPage != datas.pages}" th:href="@{/index(page=${datas.currentPage+1},rows=${datas.size})}">下一頁(yè)</a><span th:text="${#strings.concat('總計(jì)',datas.pages,'頁(yè)')}"></span></th></tr></tbody></table></div> </body> </html>啟動(dòng)類ImageConsumerApp
package com.bjsxt.img;import org.apache.dubbo.config.spring.context.annotation.EnableDubbo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplication @EnableDubbo public class ImageConsumerApp {public static void main(String[] args) {SpringApplication.run(ImageConsumerApp.class, args);} }上傳頁(yè)面
upload.html
完善功能ImageController
package com.bjsxt.img.contoller;import com.bjsxt.img.pojo.Image; import com.bjsxt.img.service.ImageService; import com.bjsxt.img.utils.FastDFSUtils; import org.csource.common.NameValuePair; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartFile;import javax.servlet.http.HttpServletResponse; import java.awt.im.InputContext; import java.io.InputStream; import java.net.URLEncoder; import java.util.Date; import java.util.HashMap; import java.util.Map;/*** 圖片服務(wù)的控制器。與客戶直接交互。*/ @Controller public class ImageController {@Autowiredprivate ImageService imageService;@Autowiredprivate FastDFSUtils utils;/*** 下載圖片* 1、 從數(shù)據(jù)庫(kù)查詢id對(duì)應(yīng)的數(shù)據(jù)* 2、 根據(jù)查詢結(jié)果到FastDFS中找文件數(shù)據(jù)* 3、 文件下載*/@GetMapping("/download")public void download(Long id, HttpServletResponse response){try {// 查詢數(shù)據(jù)Image image = imageService.getById(id);// 從FastDFS中查詢要下載的文件內(nèi)容NameValuePair[] metaDatas = new NameValuePair[3];byte[] datas = utils.downloadFile(image.getGroupName(), image.getRemoteFileName(), metaDatas);// 使用響應(yīng)輸出流,向客戶端輸出文件內(nèi)容,并提示下載。// 設(shè)置響應(yīng)頭為流輸出response.setContentType("application/octet-stream");// 獲取文件的原始名稱String fileName = "";for (NameValuePair nvp : metaDatas) {if (nvp.getName().equals("fileName")) {fileName = nvp.getValue();}}// 編碼處理,避免響應(yīng)頭設(shè)置的中文出現(xiàn)亂碼。fileName = URLEncoder.encode(fileName, "UTF-8");// 設(shè)置響應(yīng)頭,并標(biāo)記附件文件名為fileName。response.setHeader("content-disposition", "attachment;filename=" + fileName);// 輸出文件內(nèi)容到客戶端response.getOutputStream().write(datas);// 刷新輸出流緩沖。response.getOutputStream().flush();}catch(Exception e){e.printStackTrace();return ;}}/*** 刪除圖片數(shù)據(jù)* @param id* @return*/@GetMapping("/remove")public String remove(Long id){// 從數(shù)據(jù)庫(kù)查詢id對(duì)應(yīng)的Image對(duì)象Image image = imageService.getById(id);int rows = imageService.remove(id); // 刪除數(shù)據(jù)庫(kù)中的數(shù)據(jù)if(rows == 1){// 刪數(shù)據(jù)成功,需要從FastDFS中刪除對(duì)應(yīng)的圖片utils.deleteFile(image.getGroupName(), image.getRemoteFileName());}return "redirect:/index?page=1&rows=5";}/*** 保存上傳的圖片信息到數(shù)據(jù)庫(kù)*/@PostMapping("/saveImages")public String saveImages(String[] url, String[] groupName, String[] remoteFileName, String[] originFileName){if(url.length != groupName.length || url.length != remoteFileName.length || url.length != originFileName.length){// 參數(shù)個(gè)數(shù)不對(duì)。 不做任何操作,直接返回。return "redirect:/index?page=1&rows=5";}for(int i = 0; i < url.length; i++){// 循環(huán)新增圖片對(duì)象數(shù)據(jù),到數(shù)據(jù)庫(kù)Image image = new Image();image.setGroupName(groupName[i]);image.setRemoteFileName(remoteFileName[i]);image.setOriginFileName(originFileName[i]);image.setUploadTime(new Date());this.imageService.save(image);}return "redirect:/index?page=1&rows=5";}/*** 處理圖片上傳方法。* 1、 上傳文件到FastDFS* 2、 保存Image對(duì)象數(shù)據(jù)到數(shù)據(jù)庫(kù)* @param filename 上傳文件的原始名稱* @param imgFile 上傳的文件內(nèi)容。*/@PostMapping("/uploadImg")@ResponseBodypublic Object uploadImg(String filename, @RequestParam("imgFile") MultipartFile imgFile){try {InputStream inputStream = imgFile.getInputStream();byte[] datas = new byte[inputStream.available()];inputStream.read(datas);// 上傳文件String[] result = utils.uploadFile(datas,imgFile.getOriginalFilename(), "老金");Map<String, Object> map = new HashMap<>();map.put("url", "http://192.168.89.140:8888/"+result[0]+"/"+result[1]);map.put("error", 0);map.put("groupName", result[0]);map.put("remoteFileName", result[1]);map.put("originFileName", imgFile.getOriginalFilename());return map;}catch(Exception e){e.printStackTrace();Map<String, Object> map = new HashMap<>();map.put("message", "上傳文件失敗");map.put("error", 1);return map;}}/*** 跳轉(zhuǎn)到上傳圖片頁(yè)面* @return*/@GetMapping("/toUpload")public String toUpload(){return "upload";}/*** 首頁(yè)面跳轉(zhuǎn)方法。 就是分頁(yè)查詢圖片服務(wù)中所有可以管理的圖片信息。* @param page 查詢第幾頁(yè), 默認(rèn)第一頁(yè)* @param rows 查詢多少航,默認(rèn)查五行* @param model 傳遞查詢結(jié)果到視圖。* {rows:[], total:, currentPage: pages, size}* @return 視圖邏輯*/@GetMapping(value = {"/", "/index"})public String toIndex(@RequestParam(value = "page", defaultValue = "1") int page,@RequestParam(value = "rows", defaultValue = "5") int rows,Model model){// 調(diào)用服務(wù)邏輯,分頁(yè)查詢Map<String, Object> result = this.imageService.getImages(page, rows);// 查詢結(jié)果使用請(qǐng)求作用域傳遞給頁(yè)面。model.addAttribute("datas", result);return "index";} }總結(jié)
- 上一篇: OPPO A33手机出现卡顿怎么解决
- 下一篇: Feign接口转换