日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

图片管理应用

發布時間:2023/12/3 编程问答 37 豆豆
生活随笔 收集整理的這篇文章主要介紹了 图片管理应用 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

文章目錄

    • 一、簡介
    • 二、父項目
    • 三、圖片管理服務的數據庫設計
    • 四、定義module : img_pojo
    • 五、定義module : img_mapper
    • 六、定義module : img_service_api
    • 七、module : img_service_provider
    • 八、 定義module : imp_service_consumer

一、簡介

內容:

實現一個圖片管理應用。可以上傳圖片,查看圖片,刪除圖片,下載圖片。

技術:

SpringBoot:開發平臺
Dubbo:遠程服務調用技術
MyBatis:數據庫訪問
MySQL:數據庫
Zookeeper:Dubbo的注冊中心
FastDFS:集中管理所有上傳的圖片
Nginx:為FastDFS中的Storage服務器,提供一個虛擬主機,就是可以在線使用瀏覽器查看Storage內的圖片。

實現:

實體 - 定義module : img_pojo
module中定義需要的實體類型
數據訪問 - 定義module : img_mapper
module中定義需要的數據訪問接口和SQL映射文件。
服務標準 - 定義module : img_service_api
module中定義dubbo遠程訪問是的服務標準接口。只定義標準接口。
服務提供者 - 定義module : img_service_provider
module中實現img_service_api中的服務接口,并發布服務。在zk中發布服務信息。
服務消費者 - 定義module : imp_service_consumer
module中使用img_service_api中的接口,遠程調用服務提供者給予的實現。
提供客戶視圖(UI)
提供圖片上傳|下載。 圖片上傳|下載不適合使用dubbo處理。

二、父項目

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><!-- 訪問zookeeper的Java客戶端應用 --><dependency><groupId>org.apache.curator</groupId><artifactId>curator-recipes</artifactId><version>4.3.0</version></dependency><!-- 訪問zookeeper的Java客戶端應用 --><dependency><groupId>org.apache.curator</groupId><artifactId>curator-framework</artifactId><version>4.3.0</version></dependency><!-- 分頁 --><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>

三、圖片管理服務的數據庫設計

-- 創建圖片表格 create table img_manage(id bigint not null auto_increment comment '主鍵',url varchar(255) default '' comment '訪問這個圖片的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 '上傳圖片的時間',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屬性為推導屬性。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;/*** 圖片數據訪問接口。連接數據庫MySQL實現數據CRUD操作。*/ public interface ImageMapper {// 新增數據int insert(Image image);// 刪除數據int deleteByPK(Long id);// 主鍵查詢Image selectById(Long id);// 全數據查詢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;/*** 圖片服務標準接口。* dubbo的Provider需要實現這個接口提供服務* dubbo的Consumer需要使用這個接口調用服務*/ public interface ImageServiceAPI {// 新增圖片int save(Image image);// 刪除圖片int remove(Long id);// 查看圖片詳情Image getById(Long id);// 分頁查看圖片信息,使用PageHelper實現分頁。// 返回的結果是: {rows=[{圖片對象}], total=總計圖片數量, currentPage=當前頁碼, pages=總計頁數, size=每頁行數}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;/*** 服務提供者, 實現服務標準。* 這個Service注解是dubbo的Service注解* @Transactional事務管理*/ @Service public class ImageServiceImpl implements ImageServiceAPI {// 注入Mapper對象@Autowiredprivate ImageMapper imageMapper;/*** 新增圖片到數據庫* @param image 要新增的數據對象* @return*/@Override@Transactionalpublic int save(Image image) {return imageMapper.insert(image);}/*** 刪除數據* @param id 要刪除的數據主鍵* @return*/@Override@Transactionalpublic int remove(Long id) {return imageMapper.deleteByPK(id);}/*** 主鍵查詢 * 注意:查詢是只讀的,不考慮 @Transactional* @param id 要查詢的數據的主鍵* @return*/@Overridepublic Image getById(Long id) {return imageMapper.selectById(id);}/*** 分頁查詢* @param page 第幾頁* @param rows 多少行* @return*/@Overridepublic Map<String, Object> getImages(int page, int rows) {// 使用分頁查詢PageHelper.startPage(page, rows);// 分頁查詢, 返回的結果是PageHelper封裝的List的實現類型PageList<Image> list = imageMapper.select();// 使用PageInfo輔助工具對象,實現分頁數據的獲取PageInfo<Image> info = new PageInfo<>(list);// 創建返回結果Map<String, Object> result = new HashMap<>();result.put("total", info.getTotal()); // 總計數據行數result.put("rows", list); // 當前頁面的數據集合result.put("currentPage", page); // 當前是第幾頁result.put("pages", info.getPages()); // 總計多少頁result.put("size", rows); // 每頁顯示多少行。return result; } }

啟動類
com.bjsxt.img

package com.bjsxt.img;import org.apache.dubbo.config.spring.context.annotation.EnableDubbo; import org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplication @EnableDubbo @MapperScan(basePackages = {"com.bjsxt.img.mapper"}) public class ImageProviderApp {public static void main(String[] args) {SpringApplication.run(ImageProviderApp.class, args);} }

application.yml

spring:profiles:active: db dubbo:application: # dubbo應用必須提供一個唯一的命名。同名的dubbo應用自動組成集群。name: img_manage_providerprotocol:name: dubboport: 20880registry:address: zookeeper://192.168.14.129:2181config-center:timeout: 10000 server:port: 8081 pagehelper:helper-dialect: mysql

啟動zookeeper,啟動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: 80

FastDFSUtils.java

package com.bjsxt.img.utils;import org.csource.common.NameValuePair; import org.csource.fastdfs.*;import java.util.Properties;public class FastDFSUtils {// 通過static初始化代碼塊,讀取配置文件,初始化客戶端連接對象。// 客戶端連接對象,用于實現文件讀寫操作使用。private StorageClient storageClient;// 默認構造public FastDFSUtils() {// 提供默認配置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實現配置ClientGlobal.initByProperties(properties);// 創建Tracker客戶端對象TrackerClient trackerClient = new TrackerClient();// 創建Tracker服務器對象TrackerServer trackerServer = trackerClient.getConnection();// 創建Storage服務器對象StorageServer storageServer = trackerClient.getStoreStorage(trackerServer);// 創建Storage客戶端對象storageClient = new StorageClient(trackerServer, storageServer);}catch(Exception e){e.printStackTrace();// 初始化代碼塊出錯,一定要拋出錯誤,停止虛擬機。throw new ExceptionInInitializerError(e);}}/*** 文件刪除,FastDFS會自動刪除這個文件對應的metaData。就是文件名-m這個文件。*/public boolean deleteFile(String groupName, String fileName){try{// storageClient.delete_file(String groupName, String fileName);// groupName - 要刪除的文件的卷名,就是保存文件的storage服務配置中的groupName// fileName - 要刪除的文件的文件名,包含路徑地址。格式:M00/目錄/目錄/文件名.后綴名// M00代表保存文件的目錄, store_path0 。 目錄/目錄 - 保存文件的具體位置。int result = storageClient.delete_file(groupName, fileName);// 返回結果為0,代表刪除成功,其他是刪除失敗。return result == 0;}catch(Exception e){e.printStackTrace();return false;}}/*** 文件下載* @param metaDatas - 傳入一個數組,用于保存下載文件的擴展信息。如果傳入null,則不需要文件擴展信息。* 如果傳入的數組不是null,則需要文件的擴展信息。* @return 下載的文件內容*/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);// 要下載的文件的擴展信息。if(metaDatas != null) {NameValuePair[] tmp = storageClient.get_metadata(groupName, fileName);// 把查詢到的文件擴展信息。保存到傳入的數組中。for(int i = 0; i < tmp.length; i++){metaDatas[i] = tmp[i];}}// 返回下載的文件內容return datas;}catch(Exception e){e.printStackTrace();return null; // 下載失敗,返回null}}/*** 使用StorageClient對象,實現文件的上傳。*/public String[] uploadFile(byte[] datas, String fileName, String authName){try{// 文件上傳// 獲取文件的擴展名String extName = fileName.substring(fileName.lastIndexOf(".") + 1);// 創建文件擴展信息。擴展信息包括文件的原始名稱,文件的大小,文件的上傳者姓名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 - 要上傳的文件的內容* extName - 上傳的文件的擴展名* metaDatas - 上傳的文件的擴展信息是什么。 如:文件的原始名稱、文件的容量大小、文件的上傳者等。*/String[] result = storageClient.upload_file(datas, extName, metaDatas);// 上傳成功,無異常。返回字符串數組。// 字符串數組長度為2。 0下標位置是 卷名|組名。 1下標位置是 文件名(目錄/文件)// fdfs為了解決上傳的文件原始名稱沖突內容不沖突而覆蓋的問題,存儲文件的時候,會提供一個uuid文件名稱。return result;}catch(Exception e){e.printStackTrace();return null; // 異常發生,返回null。代表上傳失敗。}} }

FastDFS客戶端工具類型需要使用的自動裝配對象,用來創建工具類型的對象。
spring容器管理創建的工具類型的對象

package com.bjsxt.img.config;import com.bjsxt.img.utils.FastDFSUtils; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration;import java.util.Properties;/*** FastDFS客戶端工具類型需要使用的自動裝配對象。* 用來創建工具類型的對象。*/ @Configuration public class FastDFSAutoConfigure {/*** 依托SpringBoot配置文件特性,讀取配置文件中配置的信息。*/@Value("${fdfs.connect-timeout}")private String connectTimeout;@Value("${fdfs.network-timeout}")private String networkTimeout;@Value("${fdfs.charset}")private String charSet;@Value("${fdfs.http.tracker_http_port}")private String trackerHttpPort;@Value("${fdfs.tracker_server}")private String trackerServer;/*** 創建工具類型的對象,spring容器管理* @return*/@Beanpublic FastDFSUtils fastDFSUtils(){// 根據SpringBoot配置文件,創建一個Properties對象。Properties properties = new Properties();properties.setProperty("fastdfs.connect_timeout_in_seconds", connectTimeout);properties.setProperty("fastdfs.network_timeout_in_seconds", networkTimeout);properties.setProperty("fastdfs.charset", charSet);properties.setProperty("fastdfs.http_tracker_http_port", trackerHttpPort);properties.setProperty("fastdfs.tracker_servers", trackerServer);// 構造工具類型對象。FastDFSUtils fastDFSUtils = new FastDFSUtils(properties);return fastDFSUtils;}}

服務接口ImageService

package com.bjsxt.img.service;import com.bjsxt.img.pojo.Image;import java.util.Map;/*** 本地的服務接口*/ public interface ImageService {// 保存圖片, 新增int save(Image image);// 刪除圖片int remove(Long id);// 主鍵查詢圖片詳情Image getById(Long id);// 分頁查詢圖片信息Map<String, Object> getImages(int page, int rows); }

服務接口ImageService的實現類
ImageServiceImpl

package com.bjsxt.img.service.impl;import com.bjsxt.img.pojo.Image; import com.bjsxt.img.service.ImageService; import com.bjsxt.img.serviceapi.ImageServiceAPI; import org.apache.dubbo.config.annotation.Reference; import org.springframework.stereotype.Service;import java.util.Map;/*** 本地服務實現。要成調用Provider提供的服務。還要實現圖片的上傳下載操作。*/ @Service public class ImageServiceImpl implements ImageService {// 注入遠程服務代理對象。@Referenceprivate ImageServiceAPI serviceAPI;@Overridepublic int save(Image image) {return serviceAPI.save(image);}@Overridepublic int remove(Long id) {return serviceAPI.remove(id);}@Overridepublic Image getById(Long id) {return serviceAPI.getById(id);}@Overridepublic Map<String, Object> getImages(int page, int rows) {return this.serviceAPI.getImages(page, rows);} }

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;/*** 圖片服務的控制器。與客戶直接交互。*/ @Controller public class ImageController {@Autowiredprivate ImageService imageService;@Autowiredprivate FastDFSUtils utils;/*** 首頁面跳轉方法。 就是分頁查詢圖片服務中所有可以管理的圖片信息。* @param page 查詢第幾頁, 默認第一頁* @param rows 查詢多少航,默認查五行* @param model 傳遞查詢結果到視圖。* {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){// 調用服務邏輯,分頁查詢Map<String, Object> result = this.imageService.getImages(page, rows);// 查詢結果使用請求作用域傳遞給頁面。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>圖片管理-分頁查看</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>序號</th><th>卷名</th><th>文件原始名</th><th>上傳時間</th><th>預覽</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('總計', datas.total, '')}"></span>&nbsp;&nbsp;<a th:if="${datas.currentPage} != 1" th:href="@{/index(page=${datas.currentPage-1},rows=${datas.size})}">上一頁</a><a th:if="${datas.currentPage != datas.pages}" th:href="@{/index(page=${datas.currentPage+1},rows=${datas.size})}">下一頁</a><span th:text="${#strings.concat('總計',datas.pages,'')}"></span></th></tr></tbody></table></div> </body> </html>

啟動類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);} }

上傳頁面
upload.html

<!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><title>圖片管理-上傳圖片</title><link src="/keditor/themes/default/default.css"><script src="/keditor/kindeditor-all-min.js"></script><script src="/keditor/lang/zh_CN.js"></script><script type="text/javascript">KindEditor.ready(function(K){var params = {uploadJson: 'uploadImg' // 上傳圖片地址};var editor = K.create("#content", params);K('#img_btn').click(function(){editor.loadPlugin("multiimage", function(){editor.plugin.multiImageDialog({"clickFn":function(list){var imgView = K("#img_view");imgView.html(""); // 清空視圖內容K.each(list, function(i, n){imgView.append("<img src='"+n.url+"' style='height: 50px'/>");imgView.append("<input type='hidden' name='url' value='"+n.url+"'>");imgView.append("<input type='hidden' name='groupName' value='"+n.groupName+"'>");imgView.append("<input type='hidden' name='remoteFileName' value='"+n.remoteFileName+"'>");imgView.append("<input type='hidden' name='originFileName' value='"+n.originFileName+"'>");});editor.hideDialog(); // 隱藏上傳圖片插件}});});});});</script> </head> <body> <div style="width: 800px; margin: auto; padding-top:50px; text-align: left"><form action="/saveImages" method="post">姓名:<input type="text" name="authName"><br>圖片:<input type="button" id="img_btn" value="選擇圖片"><div id="img_view"></div><br>圖文:<textarea id="content" name="content"></textarea><br><input type="submit" value="保存"></form> </div> </body> </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;/*** 圖片服務的控制器。與客戶直接交互。*/ @Controller public class ImageController {@Autowiredprivate ImageService imageService;@Autowiredprivate FastDFSUtils utils;/*** 下載圖片* 1、 從數據庫查詢id對應的數據* 2、 根據查詢結果到FastDFS中找文件數據* 3、 文件下載*/@GetMapping("/download")public void download(Long id, HttpServletResponse response){try {// 查詢數據Image image = imageService.getById(id);// 從FastDFS中查詢要下載的文件內容NameValuePair[] metaDatas = new NameValuePair[3];byte[] datas = utils.downloadFile(image.getGroupName(), image.getRemoteFileName(), metaDatas);// 使用響應輸出流,向客戶端輸出文件內容,并提示下載。// 設置響應頭為流輸出response.setContentType("application/octet-stream");// 獲取文件的原始名稱String fileName = "";for (NameValuePair nvp : metaDatas) {if (nvp.getName().equals("fileName")) {fileName = nvp.getValue();}}// 編碼處理,避免響應頭設置的中文出現亂碼。fileName = URLEncoder.encode(fileName, "UTF-8");// 設置響應頭,并標記附件文件名為fileName。response.setHeader("content-disposition", "attachment;filename=" + fileName);// 輸出文件內容到客戶端response.getOutputStream().write(datas);// 刷新輸出流緩沖。response.getOutputStream().flush();}catch(Exception e){e.printStackTrace();return ;}}/*** 刪除圖片數據* @param id* @return*/@GetMapping("/remove")public String remove(Long id){// 從數據庫查詢id對應的Image對象Image image = imageService.getById(id);int rows = imageService.remove(id); // 刪除數據庫中的數據if(rows == 1){// 刪數據成功,需要從FastDFS中刪除對應的圖片utils.deleteFile(image.getGroupName(), image.getRemoteFileName());}return "redirect:/index?page=1&rows=5";}/*** 保存上傳的圖片信息到數據庫*/@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){// 參數個數不對。 不做任何操作,直接返回。return "redirect:/index?page=1&rows=5";}for(int i = 0; i < url.length; i++){// 循環新增圖片對象數據,到數據庫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對象數據到數據庫* @param filename 上傳文件的原始名稱* @param imgFile 上傳的文件內容。*/@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;}}/*** 跳轉到上傳圖片頁面* @return*/@GetMapping("/toUpload")public String toUpload(){return "upload";}/*** 首頁面跳轉方法。 就是分頁查詢圖片服務中所有可以管理的圖片信息。* @param page 查詢第幾頁, 默認第一頁* @param rows 查詢多少航,默認查五行* @param model 傳遞查詢結果到視圖。* {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){// 調用服務邏輯,分頁查詢Map<String, Object> result = this.imageService.getImages(page, rows);// 查詢結果使用請求作用域傳遞給頁面。model.addAttribute("datas", result);return "index";} }

總結

以上是生活随笔為你收集整理的图片管理应用的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。