2021-03-15更新

This commit is contained in:
TianSH
2021-03-15 10:15:41 +08:00
parent ee52957d31
commit 867bde24be
145 changed files with 14644 additions and 25602 deletions
+30 -113
View File
@@ -1,11 +1,11 @@
# Hellohao图床 - 全新响应式UI
# Hellohao图床 - 强大的图像托管服务程序
![Visual Studio Marketplace Rating (Stars)](https://img.shields.io/visual-studio-marketplace/stars/ritwickdey.LiveServer?style=flat-square)
![https://img.shields.io/badge/license-AGPL-blue.svg?style=flat-square](https://img.shields.io/badge/license-AGPL-blue.svg?longCache=true&style=flat-square)
![https://img.shields.io/badge/language-java-orange.svg?style=flat-square](https://img.shields.io/badge/language-java-yellow.svg?longCache=true&style=popout-square)
> 这是一个基于多家对象存储源的SpringBoot开源图床项目
> 本项目使用 Spring Boot 搭建, 针对用户更方便的管理自己的图片管理拓展功能, 支持对接`本地`、`网易`,`阿里`,`又拍`,`七牛`、`腾讯`、`FTP`等多家对象存储.
> 这是一个基于多家对象存储源的SpringBoot开源图片托管程序
> 本项目使用 Spring Boot 搭建, 针对用户更方便的管理自己的图片管理拓展功能, 支持对接`本地`、`网易`,`阿里`,`又拍`,`七牛`、`腾讯`、`FTP`、`u-file`,`B2`等多家对象存储.
> 后台对用户管理。
> 支持配置多家存储源。
> 用户注册邮箱验证,以及后台配置邮箱服务器。
@@ -13,9 +13,11 @@
## 主要功能支持:
- 多主题支持:炫酷壁纸、简约蓝白
- 支持 图片拖拽、截图软件直接(Ctrl+V)和图片URL地址上传。
- 支持对接本地、网易、阿里、又拍、七牛、腾讯、FTP等各大对象存储平台。
- 支持对接本地、网易、阿里、又拍、七牛、腾讯、FTP、u-file、B2等各大对象存储平台。
- 支持图片定期暂存(到期自动删除)
- 支持画廊分享模式(用户可把自己当前上传的图片以图片集的形式批量分享给好友)
- 支持上传者IP记录,并可配置IP黑名单操作
- 支持链接生成二维码。
- 支持开启/关闭API接口。
@@ -25,129 +27,36 @@
- 邮箱注册激活。
- 站点样式设置和上传规则配置等。
主站地址: [http://tc.hellohao.cn/](http://tc.hellohao.cn/)
主站地址: [http://tbed.hellohao.cn/](http://tbed.hellohao.cn/)
体验地址(用户名/密码均为admin):[http://129.28.173.126:8088/](http://129.28.173.126:8088/)
文档地址: [http://tbed.hellohao.cn/doc](http://tbed.hellohao.cn/doc)
文档地址: [http://doc.wwery.com/](http://doc.wwery.com/)
编译包下载: [https://github.com/Hello-hao/Tbed/releases/](https://github.com/Hello-hao/Tbed/releases/)
捐赠列表:[http://doc.wwery.com/#/reward?id=捐赠者名单](http://doc.wwery.com/#/reward?id=捐赠者名单)
开源版编译包下载(内部版请前往主站获取): [https://github.com/Hello-hao/Tbed/releases/](https://github.com/Hello-hao/Tbed/releases/)
全套部署视频教程:[https://www.bilibili.com/video/av79137056/](https://www.bilibili.com/video/av79137056/)
## 系统预览
![Hellohao.png](http://cdn.wwery.com/Hellohao/6071c0825062730.png)
![Hellohao2.png](http://cdn.wwery.com/Hellohao/eeeed0825062727.png)
![Hellohao/dec2d0616104505.png](http://cdn.wwery.com/Hellohao/dec2d0616104505.png)
![图床后台管理.png](http://cdn.wwery.com/Hellohao/c208e0825054822.png)
![图床后台管理2.png](http://cdn.wwery.com/Hellohao/6c7690825054822.png)
![图床后台管理3.png](http://cdn.wwery.com/Hellohao/2a79b0825054822.png)
![图床后台管理4.png](http://cdn.wwery.com/Hellohao/5c1800825054824.png)
## 更新日志
**2019-11-18**
√ 增加上传者ip记录
√ 增加临时期限照片显示。
√ 加固系统安全性验证,防止一些非法操作。
√ 优化后台上传图片算法。
#### 修复
修复上传时总是提示非法调用问题
修复系统部署的严重BUG
修复上传者IP地址显示准确问题
修复注册用户BUG
#### 注意:
- 如果你的图床已经在使用了。直接执行 `patch.sql` 补丁sql即可,不用清空之前的数据。
- 如果你是2019年09月份之前的版本,或者第一次安装本程序需要执行 `picturebed.sql` 完成sql文件
## 运行环境
- JDK 1.8
- MySQL
- MySQL5.5+
## 一:项目编译
(如果你的目的是为了部署自己的图床项目,可以下滑直接用编译包按照部署教程,直接可以部署。)
## 部署
### 下载项目
```git
git clone https://github.com/Hello-hao/Tbed.git
```
### 导入项目
使用自己的 Intellij IDEA 或者 Eclipse 均可.
### 导入数据库
创建数据库`picturebed`, 字符集选择 `utf8`, 排序规则选择 `utf8_general_ci`.
导入picturebed.sql
### 配置文件
### 修改配置文件
打开 `application.properties` 修改 `MySQL``服务器端口` 等连接信息.
```properties
#数据库账号
spring.datasource.username=root
#数据库密码
spring.datasource.password=root
#数据库链接地址
spring.datasource.url=jdbc:mysql://localhost:3306/picturebed?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8
#端口
server.port=8088
#鉴黄周期表达式 下方表达式为每天七点半执行
#不懂请勿乱修改。具体可以参考官方文档http://doc.wwery.com
Expression=0 30 04 * * ?
#下边的配置项不需要修改。
mybatis.configuration.map-underscore-to-camel-case=true
mybatis.mapper-locations=classpath:mapper/*.xml
logging.level.cn.hellohao.dao=debug
spring.jackson.date-format=yyyy-MM-dd HH:mm:ss
spring.jackson.time-zone=GMT+8
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.thymeleaf.cache=false
multipart.maxFileSize=10240KB
multipart.maxRequestSize=10240KB
spring.thymeleaf.mode = LEGACYHTML5
spring.http.multipart.location=/data/upload_tmp
```
### 启动项目
在完成了上述步骤后,找到 TbedApplication 启动类, 启动即可.
初始用户名:admin
初始邮箱:admin
初始密码`admin`
启动后访问地址为:http://localhost:8088 , `8088`就是你配置`server.port=8088`的端口.
## 二:编译包直接部署
> **项目搭建部署教程:** [**http://www.hellohao.cn/?p=201**](http://www.hellohao.cn/?p=201 "点击查看搭建文档")
### 部署
前提是你的服务器必须要有`JDK1.8`环境,和`mysql`数据库。
@@ -157,8 +66,6 @@ spring.http.multipart.location=/data/upload_tmp
yum install java-1.8*
```
如果你是宝塔环境,也可以在应用商店安装一个`Tomcat8`因该是自带JDK1.8环境。
`Tbed.jar``application.properties`放到服务器你想存放的目录比如`/home`,注意这两个文件必须要在同一目录下不能分开。
依次运行如下命令:
@@ -168,23 +75,32 @@ cd /home
java -jar Tbed.jar
```
然后访问`http://服务器IP:8088/`即可。
### 启动项目
启动后访问地址为:http://localhost:8088 , `8088`就是你配置`server.port=8088`的端口.
初始用户名:admin
初始邮箱:admin
初始密码`admin`
注意:上边的`/home`是你的jar包和application.properties文件放的目录。
项目运行起来不要关闭xshell窗口,否则项目将不能访问。可以使用一些后台命令把项目锁定后台。如`nohup``screen`,推荐使用`screen`
### PC客户端
![khd.gif](http://cdn.wwery.com/Hellohao/b1bb70927045346.gif)
如果你想让自己的图床拥有自己的客户端,可以加下方群,联系群主帮你对接(前提是你使用的是Hellohao图床程序搭建的网站。)
作者精力不够,工作繁忙,暂停更新
### 声明
本程序免费提供给个人用户使用,未经允许不得作为盈利商业使用,如果你想商用,请先与我们联系,分享你的利益。
本程序免费提供给个人用户使用,未经允许不得作为盈利商业使用,如果你想商用或程序定制,请先与我们联系,分享你的利益。
源码仅供感兴趣的开发者做开发逻辑参考,不得在未经开发者同意的情况下以他人名义修改并发布使用编译包。
如果你想个人修改并使用我的源码,请保留原作者的版权,并开源你修改过的源码。
### 反馈交流
**如果你遇到BUG可以去我的博客反馈**
**如果你遇到BUG可以去我的博客反馈**
Hellohao博客: [http://www.hellohao.cn/](http://www.hellohao.cn/)
欢迎加入Hellohao开发者交流群,群聊号码:**864800972**
@@ -193,4 +109,5 @@ Hellohao博客: [http://www.hellohao.cn/](http://www.hellohao.cn/)
**如果你也支持Hellohao图床,可以请我喝杯咖啡。我会持续更新Hellohao图床**
![](http://cdn.wwery.com/Hellohao/df2710722111702.jpg)
**捐赠地址:** [**http://tbed.hellohao.cn/pay**](http://tbed.hellohao.cn/pay)
+7 -1
View File
@@ -16,6 +16,7 @@
<properties>
<java.version>1.8</java.version>
<tomcat.version>9.0.30</tomcat.version>
<docker.image.prefix>springboot</docker.image.prefix>
</properties>
<dependencies>
@@ -68,6 +69,12 @@
<artifactId>java-sdk</artifactId>
<version>4.1.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-text -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-text</artifactId>
<version>1.8</version>
</dependency>
<!--七牛-->
<dependency>
<groupId>com.qiniu</groupId>
@@ -100,7 +107,6 @@
<version>4.5.16</version>
</dependency>
<!-- 定时器依赖-->
<dependency>
<groupId>org.quartz-scheduler</groupId>
+54 -26
View File
@@ -11,12 +11,24 @@
Target Server Version : 50720
File Encoding : 65001
Date: 07/11/2019 21:25:39
Date: 15/03/2021 10:08:10
*/
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for album
-- ----------------------------
DROP TABLE IF EXISTS `album`;
CREATE TABLE `album` (
`albumkey` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`albumtitle` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`createdate` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`password` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`userid` int(10) NULL DEFAULT NULL
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Table structure for code
-- ----------------------------
@@ -37,26 +49,27 @@ CREATE TABLE `config` (
`sourcekey` int(4) NULL DEFAULT NULL,
`emails` int(4) NULL DEFAULT NULL COMMENT '邮箱配置',
`webname` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '网站名',
`explain` varchar(500) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '首页左下角说明',
`video` varchar(500) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '视频地址',
`explain` varchar(1000) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`video` varchar(1000) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`backtype` varchar(500) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '背景类型',
`links` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '备案号',
`notice` varchar(500) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '公告',
`baidu` varchar(500) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '百度统计',
`domain` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '站点域名',
`background1` varchar(500) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '首页背景图',
`background2` varchar(500) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '上传页面背景图',
`links` varchar(1000) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`notice` varchar(1000) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`baidu` varchar(1000) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`domain` varchar(1000) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`background1` varchar(1000) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`background2` varchar(1000) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`sett` int(2) NOT NULL COMMENT '首页样式',
`webms` varchar(500) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`webkeywords` varchar(500) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`webfavicons` varchar(500) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`webms` varchar(1000) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`webkeywords` varchar(1000) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`webfavicons` varchar(1000) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`theme` int(4) NULL DEFAULT 1 COMMENT '主题',
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 2 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Compact;
-- ----------------------------
-- Records of config
-- ----------------------------
INSERT INTO `config` VALUES (1, 7, 1, 'Hellohao', '网站由JAVA语言编写应用SpringBoot框架开发,前端全部组件由BootStrap/Layui框架编写。由作者个人更新维护,后期会加入更全面的功能供大家使用,如有BUG请与我反馈。', 'https://hellohao-cloud.oss-cn-beijing.aliyuncs.com/Pexels.mp4', '1', '<a href=\"http://hellohao.cn/\" rel=\"nofollow\" target=\"_blank\">Hellohao开发制作</a>', '也许...|这将是最好用的图床', 'console.log(\'JS代码\');', 'http://127.0.0.1:8088', 'https://ss0.bdstatic.com/94oJfD_bAAcT8t7mm9GUKT-xh_/timg?image&quality=100&size=b4000_4000&sec=1565769264&di=74d809d6cfae81bbab83bf9d573d8f9a&src=http://pic17.nipic.com/20110917/7420038_160826355111_2.jpg', 'https://ss0.bdstatic.com/94oJfD_bAAcT8t7mm9GUKT-xh_/timg?image&quality=100&size=b4000_4000&sec=1565769264&di=74d809d6cfae81bbab83bf9d573d8f9a&src=http://pic17.nipic.com/20110917/7420038_160826355111_2.jpg', 1, NULL, NULL, NULL);
INSERT INTO `config` VALUES (1, 9, 1, 'Hellohao', '网站由JAVA语言编写应用SpringBoot框架开发,前端全部组件由BootStrap/Layui框架编写。由作者个人更新维护,感谢使用者的支持。', '', '1', '<span style=\"color:#7c7c88;\">&copy; 2019 Hellohao - All Rights Reserved - Collect from <a href=\"http://www.Hellohao.cn/\" target=\"_blank\" title=\"Hellohao\">Hellohao博客</a></span>', '也许...|这将是最好用的图床', 'console.log(\'JS代码\');', 'http://127.0.0.1:8088', 'https://s1.ax1x.com/2020/05/26/tPM6qU.jpg', '', 1, '', '', '', 1);
-- ----------------------------
-- Table structure for emailconfig
@@ -86,13 +99,24 @@ CREATE TABLE `group` (
`id` int(255) NOT NULL AUTO_INCREMENT,
`groupname` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '组名称',
`keyid` int(255) NULL DEFAULT NULL,
`usertype` int(255) NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 2 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Compact;
-- ----------------------------
-- Records of group
-- ----------------------------
INSERT INTO `group` VALUES (1, '默认群组', 5);
INSERT INTO `group` VALUES (1, '默认群组', 5, 0);
-- ----------------------------
-- Table structure for imgandalbum
-- ----------------------------
DROP TABLE IF EXISTS `imgandalbum`;
CREATE TABLE `imgandalbum` (
`imgname` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`albumkey` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`notes` varchar(1000) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT ' '
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Table structure for imgdata
@@ -108,8 +132,11 @@ CREATE TABLE `imgdata` (
`abnormal` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`source` int(2) NULL DEFAULT NULL COMMENT '存储源',
`imgtype` int(2) NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Compact;
`explains` varchar(500) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`md5key` varchar(500) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE,
INDEX `index_md5key_url`(`md5key`, `imgurl`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 58 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Compressed;
-- ----------------------------
-- Table structure for imgreview
@@ -128,7 +155,7 @@ CREATE TABLE `imgreview` (
-- ----------------------------
-- Records of imgreview
-- ----------------------------
INSERT INTO `imgreview` VALUES (1, NULL, NULL, NULL, 0, 0);
INSERT INTO `imgreview` VALUES (1, '', '', '', 0, 0);
-- ----------------------------
-- Table structure for keys
@@ -150,13 +177,13 @@ CREATE TABLE `keys` (
-- ----------------------------
INSERT INTO `keys` VALUES (1, '', '', '', '', '', 1);
INSERT INTO `keys` VALUES (2, '', '', '', '', '', 2);
INSERT INTO `keys` VALUES (3, '', '', '0', '', '', 3);
INSERT INTO `keys` VALUES (4, '', '', '', '', '', 4);
INSERT INTO `keys` VALUES (3, '1', '1', '0', '1', 'http://127.0.0.1', 3);
INSERT INTO `keys` VALUES (4, '', '', '0', '', '', 4);
INSERT INTO `keys` VALUES (5, '0', '0', '0', '0', '0', 5);
INSERT INTO `keys` VALUES (6, '', '', '', '', '', 6);
INSERT INTO `keys` VALUES (7, '', '', '', '', '', 7);
INSERT INTO `keys` VALUES (8, '', '', '', '', '', 8);
INSERT INTO `keys` VALUES (9, '', '', '', '', '', 9);
INSERT INTO `keys` VALUES (7, '1', '1', '127.0.0.1:21', '', 'http://127.0.0.1', 7);
INSERT INTO `keys` VALUES (8, '111', '222', '0', '333', 'http://127.0.0.1/', 8);
INSERT INTO `keys` VALUES (9, 'test', 'test', '123', 'testimg', 'test', 9);
INSERT INTO `keys` VALUES (10, '0', '', '0', '0', '0', 10);
-- ----------------------------
@@ -199,13 +226,14 @@ CREATE TABLE `uploadconfig` (
`api` int(2) NOT NULL COMMENT '开启api',
`visitormemory` int(10) NULL DEFAULT NULL COMMENT '游客限制大小',
`usermemory` int(10) NULL DEFAULT 0 COMMENT '用户默认大小',
`blacklist` varchar(4000) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 2 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Compact;
-- ----------------------------
-- Records of uploadconfig
-- ----------------------------
INSERT INTO `uploadconfig` VALUES (1, 3, 5, 1, 5, 'gif,jpg,jpeg,bmp,png', 1, 1, 1, 500, 1024);
INSERT INTO `uploadconfig` VALUES (1, 3, 10, 1, 5, 'gif,jpg,jpeg,bmp,png', 1, 0, 1, 500, 1024, '');
-- ----------------------------
-- Table structure for user
@@ -215,7 +243,7 @@ CREATE TABLE `user` (
`id` int(10) NOT NULL AUTO_INCREMENT COMMENT '主键',
`username` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '用户名',
`password` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '密码',
`email` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '邮箱',
`email` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`birthder` date NULL DEFAULT NULL COMMENT '注册时间',
`level` int(10) NULL DEFAULT NULL COMMENT '等级',
`uid` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '用户唯一标识',
@@ -223,12 +251,12 @@ CREATE TABLE `user` (
`memory` int(10) NULL DEFAULT NULL COMMENT '用户内存大小',
`groupid` int(255) NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 2 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Compact;
) ENGINE = InnoDB AUTO_INCREMENT = 3 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Compact;
-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES (1, 'admin', 'YWRtaW4=', 'admin', '2019-06-12', 2, 'admin', 1, 1024, 1);
INSERT INTO `user` VALUES (1, 'admin', 'YWRtaW4=', 'admin', '2019-06-12', 2, '6dfbc6d4063b484e97955148dbeab429', 1, 1024, 1);
-- ----------------------------
-- Table structure for usergroup
@@ -7,6 +7,7 @@ import cn.hellohao.utils.Print;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.MultipartConfigFactory;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
@@ -19,6 +20,7 @@ import java.util.Scanner;
@SpringBootApplication
@Configuration
@ServletComponentScan
@EnableTransactionManagement(proxyTargetClass = true)
public class TbedApplication {
@@ -37,6 +39,8 @@ public static void main(String[] args) {
factory.setMaxFileSize("102400KB"); // KB,MB
/// 总上传数据大小
factory.setMaxRequestSize("102400KB");
//factory.setLocation("/tmp");
return factory.createMultipartConfig();
}
@@ -3,6 +3,7 @@ package cn.hellohao.controller;
import cn.hellohao.pojo.*;
import cn.hellohao.pojo.vo.PageResultBean;
import cn.hellohao.service.*;
import cn.hellohao.service.impl.AlbumServiceI;
import cn.hellohao.service.impl.ImgServiceImpl;
import cn.hellohao.service.impl.UserServiceImpl;
import cn.hellohao.utils.*;
@@ -45,10 +46,16 @@ public class AdminController {
private UploadConfigService uploadConfigService;
@Autowired
private CodeService codeService;
@Autowired
private ImgAndAlbumService imgAndAlbumService;
@Autowired
private AlbumService albumService;
@Autowired
AlbumServiceI albumServiceI;
@RequestMapping(value = "/goadmin")
public String goadmin1(HttpSession session, Model model, HttpServletRequest request) {
Config config = configService.getSourceype();
User user = (User) session.getAttribute("user");
UploadConfig uploadConfig = uploadConfigService.getUpdateConfig();
Integer usermemory = imgService.getusermemory(user.getId());
@@ -65,7 +72,7 @@ public class AdminController {
model.addAttribute("levels", user.getLevel());
model.addAttribute("username", user.getUsername());
model.addAttribute("api", uploadConfig.getApi());
model.addAttribute("config", config);
model.addAttribute("memory",u.getMemory());//单位M
if(usermemory==null){
model.addAttribute("usermemory", 0);//单位M
@@ -102,7 +109,6 @@ public class AdminController {
model.addAttribute("sysetmname",sysetmname);
model.addAttribute("isarch", isarch);
model.addAttribute("jdk", jdk);
//空间大小
UploadConfig uploadConfig = uploadConfigService.getUpdateConfig();
Integer usermemory = imgService.getusermemory(u.getId());
@@ -125,7 +131,6 @@ public class AdminController {
model.addAttribute("usermemory", 0);//单位M
}else{
float d = (float) (Math.round((usermemory/1024.0F) * 100.0) / 100.0);
//Print.Normal();
model.addAttribute("usermemory", d);//单位M
}
}
@@ -147,8 +152,9 @@ public class AdminController {
if(uploadConfig.getIsupdate()!=1){
jsonObject.put("VisitorUpload", 0);//是否禁用了游客上传
}else{
Integer temp = imgService.getusermemory(0);
jsonObject.put("VisitorUpload", uploadConfig.getIsupdate());//是否禁用了游客上传
jsonObject.put("UsedSize", (imgService.getusermemory(0)/1024));//访客已用大小
jsonObject.put("UsedSize", (temp == null ? 0 : temp/1024));//访客已用大小
jsonObject.put("VisitorMemory", uploadConfig.getVisitormemory());//访客共大小
}
return jsonObject.toString();
@@ -177,9 +183,13 @@ public class AdminController {
if (u.getLevel() > 1) {
if (selecttype == 1) {
images = imgService.selectimg(img);
} else {
} else if(selecttype == 2) {
img.setUserid(u.getId());
images = imgService.selectimg(img);
}else{
img.setUserid(u.getId());
img.setSelecttype(3);
images = imgService.selectimg(img);
}
} else {
img.setUserid(u.getId());
@@ -189,8 +199,6 @@ public class AdminController {
return new PageResultBean<>(rolePageInfo.getTotal(), rolePageInfo.getList());
}
@RequestMapping(value = "/selectusertable")
@ResponseBody
public Map<String, Object> selectByFy12(HttpSession session, @RequestParam(required = false, defaultValue = "1") int page,
@@ -216,19 +224,12 @@ public class AdminController {
@PostMapping("/deleimg")
@ResponseBody
public String deleimg(HttpSession session, Integer id, Integer sourcekey) {
public String deleimg(HttpSession session, Integer id, Integer sourcekey,String imgname) {
JSONObject jsonObject = new JSONObject();
User u = (User) session.getAttribute("user");
Images images = imgService.selectByPrimaryKey(id);
Keys key = keysService.selectKeys(sourcekey);
Integer Sourcekey = GetCurrentSource.GetSource(u.getId());
Boolean b =false;
if(Sourcekey==5){
b =true;
}else{
b = StringUtils.doNull(Sourcekey,key);//判断对象是否有空值
}
if(b){
ImgServiceImpl de = new ImgServiceImpl();
if (key.getStorageType() == 1) {
de.delect(key, images.getImgname());
@@ -244,57 +245,53 @@ public class AdminController {
de.delectCOS(key, images.getImgname());
}else if (key.getStorageType() == 7) {
de.delectFTP(key, images.getImgname());
}else if (key.getStorageType() == 8) {
de.delectUFile(key, images.getImgname());
}else {
System.err.println("未获取到对象存储参数,删除失败。");
}
Integer ret = imgService.deleimg(id);
if(ret>0){ imgAndAlbumService.deleteImgAndAlbum(imgname);}
Integer count = 0;
if (ret > 0) {
jsonObject.put("usercount", imgService.countimg(u.getId()));
jsonObject.put("count", imgService.counts(null));
count = 1;
imgAndAlbumService.deleteImgAndAlbum(imgname);//关联表删除关于这张照片的所有记录
} else {
count = 0;
}
jsonObject.put("val", count);
}else{
jsonObject.put("val", 0);
}
return jsonObject.toString();
}
@PostMapping("/deleallimg")
@ResponseBody
public String deleallimg(HttpSession session, @RequestParam("ids[]") Integer[] ids) {
public String deleallimg(HttpSession session, @RequestParam("ids[]") Integer[] ids,@RequestParam("sources[]") Integer[] sources,
@RequestParam("imgnames[]") String[] imgnames) {
JSONObject jsonObject = new JSONObject();
Integer v = 0;
ImgServiceImpl de = new ImgServiceImpl();
User u = (User) session.getAttribute("user");
Integer Sourcekey = GetCurrentSource.GetSource(u.getId());
for (int i = 0; i < ids.length; i++) {
Images images = imgService.selectByPrimaryKey(ids[i]);
Keys key = keysService.selectKeys(images.getSource());
Boolean b =false;
if(Sourcekey==5){
b =true;
}else{
b = StringUtils.doNull(Sourcekey,key);//判断对象是否有空值
}
if(b){
Keys key = keysService.selectKeys(sources[i]);
if (key.getStorageType() == 1) {
de.delect(key, images.getImgname());
de.delect(key, imgnames[i]);
} else if (key.getStorageType() == 2) {
de.delectOSS(key, images.getImgname());
de.delectOSS(key, imgnames[i]);
} else if (key.getStorageType() == 3) {
de.delectUSS(key, images.getImgname());
de.delectUSS(key, imgnames[i]);
} else if (key.getStorageType() == 4) {
de.delectKODO(key, images.getImgname());
de.delectKODO(key, imgnames[i]);
} else if (key.getStorageType() == 5) {
LocUpdateImg.deleteLOCImg(images.getImgname());
LocUpdateImg.deleteLOCImg(imgnames[i]);
}else if (key.getStorageType() == 6) {
de.delectCOS(key, images.getImgname());
de.delectCOS(key, imgnames[i]);
}else if (key.getStorageType() == 7) {
de.delectFTP(key, images.getImgname());
de.delectFTP(key, imgnames[i]);
}else if (key.getStorageType() == 8) {
de.delectUFile(key, imgnames[i]);
}else {
System.err.println("未获取到对象存储参数,删除失败。");
}
@@ -303,10 +300,8 @@ public class AdminController {
v = 0;
} else {
v = 1;
imgAndAlbumService.deleteImgAndAlbum(imgnames[i]);//关联表删除关于这张照片的所有记录
}
}else {
v = 0;
}
}
jsonObject.put("val", v);
jsonObject.put("usercount", imgService.countimg(u.getId()));
@@ -344,7 +339,6 @@ public class AdminController {
session.removeAttribute("user");
session.invalidate();
}
// -1 用户名重复
return jsonArray.toString();
}
//进入api
@@ -359,7 +353,6 @@ public class AdminController {
return "admin/api";
}
@PostMapping(value = "/kuorong")
@ResponseBody
public String kuorong(HttpSession session, String codestring) {
@@ -397,4 +390,61 @@ public class AdminController {
}
@RequestMapping(value = "/albumlist")
public String albumlist(HttpSession session, Model model) {
Config config = configService.getSourceype();
User u = (User) session.getAttribute("user");
model.addAttribute("config", config);
model.addAttribute("level", u.getLevel());
model.addAttribute("email", u.getEmail());
model.addAttribute("loginid", 100);
return "admin/albumlist";
}
@PostMapping("/getAlbumURLList")
@ResponseBody
public Map<String, Object> getAlbumURLList (HttpSession session,@RequestParam(required = false, defaultValue = "1") int page,
@RequestParam(required = false) int limit,Album album){
User u = (User) session.getAttribute("user");
PageHelper.startPage(page, limit);
List<Album> list = null;
if (u.getLevel() == 2) {
album.setUserid(null);
list = albumServiceI.selectAlbumURLList(album);
PageInfo<Album> rolePageInfo = new PageInfo<>(list);
Map<String, Object> map = new HashMap<String, Object>();
map.put("code", 0);
map.put("msg", "");
map.put("count", rolePageInfo.getTotal());
map.put("data", rolePageInfo.getList());
return map;
} else {
album.setUserid(u.getId());
list = albumServiceI.selectAlbumURLList(album);
PageInfo<Album> rolePageInfo = new PageInfo<>(list);
Map<String, Object> map = new HashMap<String, Object>();
map.put("code", 0);
map.put("msg", "");
map.put("count", rolePageInfo.getTotal());
map.put("data", rolePageInfo.getList());
return map;
}
}
@RequestMapping("/delAlbum")
@ResponseBody
public Integer delAlbum(String albumkey){
Integer ret = albumServiceI.delete(albumkey);
return ret;
}
@RequestMapping("/delAlbumAll")
@ResponseBody
public Integer delAlbumAll( @RequestParam("albumkeyArr[]") String[] albumkeyArr ){
Integer ret = albumServiceI.deleteAll(albumkeyArr);
return ret;
}
}
@@ -8,6 +8,7 @@ import cn.hellohao.utils.Print;
import cn.hellohao.utils.StringUtils;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
@@ -19,6 +20,7 @@ import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
@Controller
@RequestMapping("/admin/root")
@@ -55,17 +57,15 @@ public class AdminRootController {
User u = (User) session.getAttribute("user");
Integer Sourcekey = GetCurrentSource.GetSource(u.getId());
Keys key= keysService.selectKeys(Sourcekey);
Boolean b = StringUtils.doNull(Sourcekey,key);
//Boolean b = StringUtils.doNull(Sourcekey,key);
Integer StorageType = 0;
if(Sourcekey!=5){
if(b){
model.addAttribute("AccessKey", key.getAccessKey());
model.addAttribute("AccessSecret", key.getAccessSecret());
model.addAttribute("Endpoint", key.getEndpoint());
model.addAttribute("Bucketname", key.getBucketname());
model.addAttribute("RequestAddress", key.getRequestAddress());
model.addAttribute("StorageType", Sourcekey);
}
model.addAttribute("AccessKey", key.getAccessKey());
model.addAttribute("AccessSecret", key.getAccessSecret());
model.addAttribute("Endpoint", key.getEndpoint());
model.addAttribute("Bucketname", key.getBucketname());
model.addAttribute("RequestAddress", key.getRequestAddress());
model.addAttribute("StorageType", Sourcekey);
if(Sourcekey==4){
model.addAttribute("Endpoint2", key.getEndpoint());
}else{
@@ -107,12 +107,11 @@ public class AdminRootController {
config.setSourcekey(key.getStorageType());
Integer val = configService.setSourceype(config);
Integer ret = -2;
//修改完初始化
if(key.getStorageType()==1){
ret =nOSImageupload.Initialize(key);//实例化网易
ret =nOSImageupload.Initialize(key);
}else if (key.getStorageType()==2){
ret = OSSImageupload.Initialize(key);
}else if(key.getStorageType()==3){
}else if(key.getStorageType()==3 ){
ret = USSImageupload.Initialize(key);
}else if(key.getStorageType()==4){
ret = KODOImageupload.Initialize(key);
@@ -120,6 +119,8 @@ public class AdminRootController {
ret = COSImageupload.Initialize(key);
}else if(key.getStorageType()==7){
ret = FTPImageupload.Initialize(key);
}else if(key.getStorageType()==8){
ret = UFileImageupload.Initialize(key);
}
else{
Print.Normal("为获取到存储参数,或者使用存储源是本地的。");
@@ -127,7 +128,6 @@ public class AdminRootController {
if(ret>0){
ret = keysService.updateKey(key);
}
//-1 对象存储有参数为空,初始化失败
//0,保存失败
//1 正确
@@ -200,9 +200,14 @@ public class AdminRootController {
@PostMapping("/setisok")
@ResponseBody
public String setisok(HttpSession session, User user) {
Integer ret = userService.setisok(user);
JSONArray jsonArray = new JSONArray();
jsonArray.add(ret);
User u = (User) session.getAttribute("user");
if(u.getId()==user.getId()){
jsonArray.add(-2);
}else{
Integer ret = userService.setisok(user);
jsonArray.add(ret);
}
return jsonArray.toString();
}
@@ -261,4 +266,40 @@ public class AdminRootController {
return Integer.parseInt( result );
}
@PostMapping("/tocheck")
@ResponseBody
public JSONObject tocheck() {
JSONObject jsonObject = new JSONObject();
List<Keys> keylist = keysService.getKeys();
for (Keys key : keylist) {
if(key.getStorageType()!=0 && key.getStorageType()!=null){
int ret =0;
if(key.getStorageType()==1){
ret =NOSImageupload.Initialize(key);
jsonObject.put(key.getStorageType().toString(),ret);
}else if (key.getStorageType()==2){
ret =OSSImageupload.Initialize(key);
jsonObject.put(key.getStorageType().toString(),ret);
}else if(key.getStorageType()==3){
ret = USSImageupload.Initialize(key);
jsonObject.put(key.getStorageType().toString(),ret);
}else if(key.getStorageType()==4){
ret = KODOImageupload.Initialize(key);
jsonObject.put(key.getStorageType().toString(),ret);
}else if(key.getStorageType()==6){
ret = COSImageupload.Initialize(key);
jsonObject.put(key.getStorageType().toString(),ret);
}else if(key.getStorageType()==7){
ret = FTPImageupload.Initialize(key);
jsonObject.put(key.getStorageType().toString(),ret);
}else if(key.getStorageType()==8){
ret = UFileImageupload.Initialize(key);
jsonObject.put(key.getStorageType().toString(),ret);
}
}
}
jsonObject.put("5",1);
return jsonObject;
}
}
@@ -0,0 +1,179 @@
package cn.hellohao.controller;
import cn.hellohao.pojo.*;
import cn.hellohao.service.*;
import cn.hellohao.service.impl.AlbumServiceI;
import cn.hellohao.service.impl.ImgAndAlbumServiceImpl;
import cn.hellohao.utils.GetCurrentSource;
import cn.hellohao.utils.Print;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.*;
/**
* @author Hellohao
* @version 1.0
* @date 2019/12/17 11:25
*/
@Controller
public class AlbumController {
@Autowired
AlbumServiceI albumServiceI;
@Autowired
private ConfigService configService;
@Autowired
private ImgService imgService;
@Autowired
ImgAndAlbumService imgAndAlbumService;
@Autowired
private UploadConfigService uploadConfigService;
@RequestMapping("/addalbum")
public String addalbum(HttpSession session,Model model) {
UploadConfig updateConfig = uploadConfigService.getUpdateConfig();
User u = (User) session.getAttribute("user");
Integer sourcekey = 0;
if (u == null) {
sourcekey = GetCurrentSource.GetSource(null);
} else {
sourcekey = GetCurrentSource.GetSource(u.getId());
}
model.addAttribute("urltype",updateConfig.getUrltype());
model.addAttribute("sourcekey",sourcekey);
return "album/addalbum";
}
@PostMapping("/SaveForAlbum")
@ResponseBody
public Msg SaveForAlbum(HttpSession session,@RequestParam("imgarr[]") String[] imgarr, @RequestParam("aboutarr[]") String[] aboutarr,
String albumtitle, String password){
Msg msg = new Msg();
User u = (User) session.getAttribute("user");
String uuid = "TOALBUM"+ UUID.randomUUID().toString().replace("-", "").toLowerCase().substring(0,5)+"N";
Integer ret =0;
Integer temp = 0;
Integer temp2 = 0;
SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd");
for (int i = 0; i < imgarr.length; i++) {
Album album = new Album();
ImgAndAlbum imgAndAlbum = new ImgAndAlbum();
album.setAlbumtitle(albumtitle);
album.setCreatedate(df.format(new Date()));
album.setPassword(password);
album.setAlbumkey(uuid);
if(u==null){
album.setUserid(0);
}else{
album.setUserid(u.getId());
}
String imgurl = "";
Integer sourcekey = 0;
UploadConfig updateConfig = uploadConfigService.getUpdateConfig();
if(updateConfig.getUrltype()==2){
imgurl = imgarr[i];
}else{
if (u == null) {
//sourcekey = GetCurrentSource.GetSource(null);
imgurl="tourist/"+imgarr[i];
} else {
//sourcekey = GetCurrentSource.GetSource(u.getId());
imgurl=u.getUsername()+"/"+imgarr[i];
}
}
imgAndAlbum.setImgname(imgarr[i]);
imgAndAlbum.setAlbumkey(uuid);
imgAndAlbum.setNotes(aboutarr[i]);
if(temp==0){
temp2 = albumServiceI.addAlbum(album);
temp = 1;
}
if(temp2>0){
ret = albumServiceI.addAlbumForImgAndAlbumMapper(imgAndAlbum);
}
}
if(ret>0){
msg.setCode("200");
msg.setInfo("成功创建画廊链接:");
msg.setData(configService.getSourceype().getDomain()+"/"+uuid);
}else{
msg.setCode("500");
msg.setInfo("创建画廊链接失败:");
}
return msg;
}
@RequestMapping("/TOALBUM{key}N")
public String selectByFy(@PathVariable("key") String key, Model model) {
Album album = new Album();
album.setAlbumkey("TOALBUM"+key+"N");
Album a = albumServiceI.selectAlbum(album);
Config config = configService.getSourceype();
model.addAttribute("webname",config.getWebname());
model.addAttribute("domain",config.getDomain());
model.addAttribute("ico",config.getWebfavicons());
if(a!=null){
model.addAttribute("obj",a);
model.addAttribute("album",1);
if(a.getPassword()!=null && !a.getPassword().equals("")){
model.addAttribute("passType","1");
}else{
model.addAttribute("passType","0");
}
}else{
model.addAttribute("album",0);
}
return "album/album_new";
}
@PostMapping("/getAlbumList")
@ResponseBody
public Msg getAlbumList(String albumkey,String password){
Msg msg = new Msg();
Album album = new Album();
album.setAlbumkey(albumkey);
Album a = albumServiceI.selectAlbum(album);
if(a==null){
msg.setCode("404");
msg.setInfo("画廊地址不存在");
return msg;
}
Config config = configService.getSourceype();
JSONObject jsonObject = new JSONObject();
if(a!=null){
if(a.getPassword()==null){
List<Images> imagesList = imgAndAlbumService.selectImgForAlbumkey(albumkey);
msg.setCode("200");
jsonObject.put("imagesList",imagesList);
}else{
if(a.getPassword().equals(password)){
List<Images> imagesList = imgAndAlbumService.selectImgForAlbumkey(albumkey);
msg.setCode("200");
jsonObject.put("imagesList",imagesList);
}else{
msg.setCode("403");
msg.setInfo("画廊密码错误");
}
}
jsonObject.put("titlename",a.getAlbumtitle());
}
jsonObject.put("webname",config.getWebname());
msg.setData(jsonObject);
return msg;
}
@RequestMapping("/addalbum_new")
public String addalbum2() {
return "album/album_new";
}
}
@@ -4,6 +4,7 @@ import cn.hellohao.pojo.*;
import cn.hellohao.service.*;
import cn.hellohao.service.impl.*;
import cn.hellohao.utils.*;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
@@ -13,7 +14,11 @@ import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.FileInputStream;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.*;
@@ -47,7 +52,7 @@ public class ClientController {
@Autowired
private FTPImageupload ftpImageupload;
@Autowired
private DomainService domainService;
private UFileImageupload uFileImageupload;
@Autowired
private ImgService imgService;
@@ -64,15 +69,13 @@ public class ClientController {
UploadConfig uploadConfig = uploadConfigService.getUpdateConfig();
if (uploadConfig.getApi() == 1) {
if (email != null && pass != null) {
Integer ret = userService.login(email, Base64Encryption.encryptBASE64(pass.getBytes()));
Integer ret = userService.login(email, Base64Encryption.encryptBASE64(pass.getBytes()),null);
if (ret > 0) {
User user = userService.getUsers(email);
if (user.getIsok() == 1) {
User u = userService.getUsers(email);
Config config = configService.getSourceype();//查询当前系统使用的存储源类型。
Integer Sourcekey = GetCurrentSource.GetSource(u.getId());
Keys key = keysService.selectKeys(Sourcekey);
if (key.getStorageType() != 0 && key.getStorageType() != null) {
if (key.getStorageType() == 1) {
@@ -87,133 +90,129 @@ public class ClientController {
COSImageupload.Initialize(key);
} else if (key.getStorageType() == 7) {
FTPImageupload.Initialize(key);
} else {
} else if(key.getStorageType()==8){
UFileImageupload.Initialize(key);
}else {
System.err.println("客户端:未获取到对象存储参数,初始化失败。");
}
}
Print.Normal("客户端:初始化上传。");
Boolean b = false;
if (Sourcekey == 5) {
b = true;
long stime = System.currentTimeMillis();
String userpath = "tourist";
if (uploadConfig.getUrltype() == 2) {
java.text.DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
userpath = dateFormat.format(new Date());
} else {
b = StringUtils.doNull(Sourcekey, key);//判断对象是否有空值
if (u != null) {
userpath = u.getUsername();
}
}
if (b) {
long stime = System.currentTimeMillis();
String userpath = "tourist";
if (uploadConfig.getUrltype() == 2) {
java.text.DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
userpath = dateFormat.format(new Date());
} else {
if (u != null) {
userpath = u.getUsername();
}
Map<String, MultipartFile> map = new HashMap<>();
for (MultipartFile multipartFile : file) {
//获取文件名
String fileName = multipartFile.getOriginalFilename();
String lastname = fileName.substring(fileName.lastIndexOf(".") + 1);//获取文件后缀
if (!multipartFile.isEmpty()) { //判断文件是否为空
map.put(lastname, multipartFile);
}
Map<String, MultipartFile> map = new HashMap<>();
for (MultipartFile multipartFile : file) {
//获取文件名
String fileName = multipartFile.getOriginalFilename();
String lastname = fileName.substring(fileName.lastIndexOf(".") + 1);//获取文件后缀
if (!multipartFile.isEmpty()) { //判断文件是否为空
map.put(lastname, multipartFile);
}
Map<ReturnImage, Integer> m = null;
Map<ReturnImage, Integer> m2 = null;
if (key.getStorageType() == 1) {
m = nOSImageupload.clientuploadNOS(map, userpath, uploadConfig);
} else if (key.getStorageType() == 2) {
m = ossImageupload.clientuploadOSS(map, userpath, uploadConfig);
} else if (key.getStorageType() == 3) {
m = ussImageupload.clientuploadUSS(map, userpath, uploadConfig);
} else if (key.getStorageType() == 4) {
m = kodoImageupload.clientuploadKODO(map, userpath, uploadConfig);
} else if (key.getStorageType() == 5) {
m2 = LocUpdateImg.clientLocUpdateImg(map, userpath, uploadConfig);
} else if (key.getStorageType() == 6) {
m = cosImageupload.clientuploadCOS(map, userpath, uploadConfig);
} else if (key.getStorageType() == 7) {
m = ftpImageupload.clientuploadFTP(map, userpath, uploadConfig);
} else if (key.getStorageType() == 8) {
m = uFileImageupload.clientuploadUSS(map, userpath, uploadConfig);
} else {
System.err.println("未获取到对象存储参数,上传失败。");
}
Images img = new Images();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
String times = df.format(new Date());
System.out.println("上传图片的时间是:" + times);
if (key.getStorageType() == 5) {
for (Map.Entry<ReturnImage, Integer> entry : m2.entrySet()) {
JSONObject jsonObject = new JSONObject();
jsonObject.put("Imgname", entry.getKey().getImgname());
if (key.getStorageType() == 5) {
if (config.getDomain() != null) {
jsonObject.put("Imgurl", config.getDomain() + "/" + entry.getKey().getImgurl());
img.setImgurl(config.getDomain() + "/" + entry.getKey().getImgurl());//图片链接
} else {
jsonObject.put("Imgurl", config.getDomain() + "/" + entry.getKey().getImgurl());
img.setImgurl("http://" + IPPortUtil.getLocalIP() + ":" + IPPortUtil.getLocalPort() + "/" + entry.getKey().getImgurl());//图片链接
}
} else {
jsonObject.put("Imgname", entry.getKey().getImgurl());
img.setImgurl(entry.getKey().getImgurl());//图片链接
}
}
Map<ReturnImage, Integer> m = null;
Map<ReturnImage, Integer> m2 = null;
if (key.getStorageType() == 1) {
m = nOSImageupload.clientuploadNOS(map, userpath, uploadConfig);
} else if (key.getStorageType() == 2) {
m = ossImageupload.clientuploadOSS(map, userpath, uploadConfig);
} else if (key.getStorageType() == 3) {
m = ussImageupload.clientuploadUSS(map, userpath, uploadConfig);
} else if (key.getStorageType() == 4) {
m = kodoImageupload.clientuploadKODO(map, userpath, uploadConfig);
} else if (key.getStorageType() == 5) {
m2 = LocUpdateImg.clientuploadFTP(map, userpath, uploadConfig);
} else if (key.getStorageType() == 6) {
m = cosImageupload.clientuploadCOS(map, userpath, uploadConfig);
} else if (key.getStorageType() == 7) {
m = ftpImageupload.clientuploadFTP(map, userpath, uploadConfig);
} else {
System.err.println("未获取到对象存储参数,上传失败。");
}
Images img = new Images();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
String times = df.format(new Date());
System.out.println("上传图片的时间是:" + times);
if (key.getStorageType() == 5) {
for (Map.Entry<ReturnImage, Integer> entry : m2.entrySet()) {
JSONObject jsonObject = new JSONObject();
jsonObject.put("Imgname", entry.getKey().getImgname());
if (key.getStorageType() == 5) {
if (config.getDomain() != null) {
jsonObject.put("Imgurl", config.getDomain() + "/links/" + entry.getKey().getImgurl());
img.setImgurl(config.getDomain() + "/links/" + entry.getKey().getImgurl());//图片链接
} else {
jsonObject.put("Imgurl", config.getDomain() + "/links/" + entry.getKey().getImgurl());
img.setImgurl("http://" + IPPortUtil.getLocalIP() + ":" + IPPortUtil.getLocalPort() + "/links/" + entry.getKey().getImgurl());//图片链接
}
} else {
jsonObject.put("Imgname", entry.getKey().getImgurl());
img.setImgurl(entry.getKey().getImgurl());//图片链接
}
img.setUpdatetime(times);
img.setSource(key.getStorageType());
if (u == null) {
img.setUserid(0);//用户id
} else {
img.setUserid(u.getId());//用户id
}
img.setSizes((entry.getValue()));
img.setImgname(SetText.getSubString(entry.getKey().getImgurl(), key.getRequestAddress() + "/", ""));
img.setAbnormal(userip);
img.setImgtype(0);
//-1证明超出大小,
if (entry.getValue() != -1) {
userService.insertimg(img);
}
long etime = System.currentTimeMillis();
System.out.println("上传图片所用时长:" + String.valueOf(etime - stime) + "ms");
jsonArray.add(jsonObject);
img.setUpdatetime(times);
img.setSource(key.getStorageType());
if (u == null) {
img.setUserid(0);//用户id
} else {
img.setUserid(u.getId());//用户id
}
} else {
for (Map.Entry<ReturnImage, Integer> entry : m.entrySet()) {
JSONObject jsonObject = new JSONObject();
jsonObject.put("Imgname", entry.getKey().getImgname());
if (key.getStorageType() == 5) {
if (config.getDomain() != null) {
jsonObject.put("Imgurl", config.getDomain() + "/links/" + entry.getKey().getImgurl());
img.setImgurl(config.getDomain() + "/links/" + entry.getKey().getImgurl());//图片链接
} else {
jsonObject.put("Imgurl", config.getDomain() + "/links/" + entry.getKey().getImgurl());
img.setImgurl("http://" + IPPortUtil.getLocalIP() + ":" + IPPortUtil.getLocalPort() + "/links/" + entry.getKey().getImgurl());//图片链接
}
} else {
jsonObject.put("Imgurl", entry.getKey().getImgurl());
img.setImgurl(entry.getKey().getImgurl());//图片链接
}
img.setUpdatetime(times);
img.setSource(key.getStorageType());
if (u == null) {
img.setUserid(0);//用户id
} else {
img.setUserid(u.getId());//用户id
}
img.setSizes((entry.getValue())/1024);
img.setImgname(SetText.getSubString(entry.getKey().getImgurl(), key.getRequestAddress() + "/", ""));
img.setAbnormal(userip);
img.setImgtype(0);
//-1证明超出大小,
if (entry.getValue() != -1) {
userService.insertimg(img);
}
long etime = System.currentTimeMillis();
System.out.println("上传图片所用时长:" + String.valueOf(etime - stime) + "ms");
jsonArray.add(jsonObject);
img.setSizes((entry.getValue()));
img.setImgname(SetText.getSubString(entry.getKey().getImgurl(), key.getRequestAddress() + "/", ""));
img.setAbnormal(userip);
img.setImgtype(0);
//-1证明超出大小,
if (entry.getValue() != -1) {
userService.insertimg(img);
}
long etime = System.currentTimeMillis();
System.out.println("上传图片所用时长:" + String.valueOf(etime - stime) + "ms");
jsonArray.add(jsonObject);
}
resultBean = ResultBean.success(jsonArray);
} else {resultBean = ResultBean.error(-1, "服务器内部错误,请联系管理员");}
} else {
for (Map.Entry<ReturnImage, Integer> entry : m.entrySet()) {
JSONObject jsonObject = new JSONObject();
jsonObject.put("Imgname", entry.getKey().getImgname());
if (key.getStorageType() == 5) {
if (config.getDomain() != null) {
jsonObject.put("Imgurl", config.getDomain() + "/" + entry.getKey().getImgurl());
img.setImgurl(config.getDomain() + "/" + entry.getKey().getImgurl());//图片链接
} else {
jsonObject.put("Imgurl", config.getDomain() + "/" + entry.getKey().getImgurl());
img.setImgurl("http://" + IPPortUtil.getLocalIP() + ":" + IPPortUtil.getLocalPort() + "/" + entry.getKey().getImgurl());//图片链接
}
} else {
jsonObject.put("Imgurl", entry.getKey().getImgurl());
img.setImgurl(entry.getKey().getImgurl());//图片链接
}
img.setUpdatetime(times);
img.setSource(key.getStorageType());
if (u == null) {
img.setUserid(0);//用户id
} else {
img.setUserid(u.getId());//用户id
}
img.setSizes((entry.getValue())/1024);
img.setImgname(SetText.getSubString(entry.getKey().getImgurl(), key.getRequestAddress() + "/", ""));
img.setAbnormal(userip);
img.setImgtype(0);
//-1证明超出大小,
if (entry.getValue() != -1) {
userService.insertimg(img);
}
long etime = System.currentTimeMillis();
System.out.println("上传图片所用时长:" + String.valueOf(etime - stime) + "ms");
jsonArray.add(jsonObject);
}
}
resultBean = ResultBean.success(jsonArray);
}
} else {resultBean = ResultBean.error(-2, "此用户信息不正确。");}
} else {resultBean = ResultBean.error(-3, "邮箱密码为空");}
@@ -232,7 +231,7 @@ public class ClientController {
UploadConfig uploadConfig = uploadConfigService.getUpdateConfig();
if (uploadConfig.getApi() == 1) {
if (email != null && pass != null) {
Integer ret = userService.login(email, Base64Encryption.encryptBASE64(pass.getBytes()));
Integer ret = userService.login(email, Base64Encryption.encryptBASE64(pass.getBytes()),null);
if (ret > 0) {
User u = userService.getUsers(email);
Config config = configService.getSourceype();//查询当前系统使用的存储源类型。
@@ -262,11 +261,6 @@ public class ClientController {
Integer youke = uploadConfig.getFilesizetourists();
Integer yonghu = uploadConfig.getFilesizeuser();
String uuid= UUID.randomUUID().toString().replace("-", "");
Boolean bo =false;
if(Sourcekey==5){
bo =true;
}else{bo = StringUtils.doNull(Sourcekey,key);//判断对象是否有空值
}
// //容量判断
if(u==null){
memory = uploadConfig.getVisitormemory();
@@ -278,191 +272,186 @@ public class ClientController {
if(usermemory==null){usermemory = 0;}
}
Print.warning("上传地址是:"+request.getSession().getServletContext().getRealPath("/")+"/hellohaotmp/");
if(bo){
if(usermemory/1024<memory){
long stime = System.currentTimeMillis();
if(u!=null){
if(imgsize>0 && imgsize<=(yonghu*1024*1024)){
try{
boolean bl =ImgUrlUtil.downLoadFromUrl(imgurl,
uuid, request.getSession().getServletContext().getRealPath("/")+"/hellohaotmp/");
if(bl==true){
FileInputStream is = new FileInputStream(request.getSession().getServletContext().getRealPath("/")+"/hellohaotmp/"+uuid);
byte[] b = new byte[3];
is.read(b, 0, b.length);
String xxx = ImgUrlUtil.bytesToHexString(b);
xxx = xxx.toUpperCase();
String ooo = TypeDict.checkType(xxx);
if(is!=null){
is.close();
if(usermemory/1024<memory){
long stime = System.currentTimeMillis();
if(u!=null){
if(imgsize>0 && imgsize<=(yonghu*1024*1024)){
try{
boolean bl =ImgUrlUtil.downLoadFromUrl(imgurl,
uuid, request.getSession().getServletContext().getRealPath("/")+"/hellohaotmp/");
if(bl==true){
FileInputStream is = new FileInputStream(request.getSession().getServletContext().getRealPath("/")+"/hellohaotmp/"+uuid);
byte[] b = new byte[3];
is.read(b, 0, b.length);
String xxx = ImgUrlUtil.bytesToHexString(b);
xxx = xxx.toUpperCase();
String ooo = TypeDict.checkType(xxx);
if(is!=null){
is.close();
}
if(!ooo.equals("0000")){
Map<String, String> map = new HashMap<>();
map.put(ooo, request.getSession().getServletContext().getRealPath("/")+"/hellohaotmp/"+uuid);
Map<ReturnImage, Integer> m = null;
if(key.getStorageType()==1){
m = nOSImageupload.Imageupload(null, userpath,map,setday);
}else if (key.getStorageType()==2){
m = ossImageupload.ImageuploadOSS(null, userpath,map,setday);
}else if(key.getStorageType()==3 ){
m = ussImageupload.ImageuploadUSS(null, userpath,map,setday);
}else if(key.getStorageType()==4){
m = kodoImageupload.ImageuploadKODO(null, userpath,map,setday);
}else if(key.getStorageType()==5){
m = LocUpdateImg.ImageuploadLOC(null,userpath,map,setday);
}else if(key.getStorageType()==6){
m = cosImageupload.ImageuploadCOS(null,userpath,map,setday);
}else if(key.getStorageType()==7){
m = ftpImageupload.ImageuploadFTP(null,userpath,map,setday);
}else if(key.getStorageType()==8){
m = uFileImageupload.ImageuploadUSS(null, userpath,map,setday);
}
if(!ooo.equals("0000")){
Map<String, String> map = new HashMap<>();
map.put(ooo, request.getSession().getServletContext().getRealPath("/")+"/hellohaotmp/"+uuid);
Map<ReturnImage, Integer> m = null;
if(key.getStorageType()==1){
m = nOSImageupload.Imageupload(null, userpath,map,setday);
}else if (key.getStorageType()==2){
m = ossImageupload.ImageuploadOSS(null, userpath,map,setday);
}else if(key.getStorageType()==3){
m = ussImageupload.ImageuploadUSS(null, userpath,map,setday);
}else if(key.getStorageType()==4){
m = kodoImageupload.ImageuploadKODO(null, userpath,map,setday);
}else if(key.getStorageType()==5){
m = LocUpdateImg.ImageuploadLOC(null,userpath,map,setday);
}else if(key.getStorageType()==6){
m = cosImageupload.ImageuploadCOS(null,userpath,map,setday);
}else if(key.getStorageType()==7){
m = ftpImageupload.ImageuploadFTP(null,userpath,map,setday);
}
else{
System.err.println("未获取到对象存储参数,上传失败。");
}
Images img = new Images();
SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd");
String times = df.format(new Date());
System.out.println("上传图片的时间是:"+times);
for (Map.Entry<ReturnImage, Integer> entry : m.entrySet()) {
if(key.getStorageType()==5){
if(config.getDomain()!=null){
jsonArray.add(config.getDomain()+"/links/"+entry.getKey().getImgurl());
img.setImgurl(config.getDomain()+"/links/"+entry.getKey().getImgurl());//图片链接
}else{
jsonArray.add(config.getDomain()+"/links/"+entry.getKey().getImgurl());
img.setImgurl("http://"+IPPortUtil.getLocalIP()+":"+IPPortUtil.getLocalPort()+"/links/"+entry.getKey().getImgurl());//图片链接
}
else{
System.err.println("未获取到对象存储参数,上传失败。");
}
Images img = new Images();
SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd");
String times = df.format(new Date());
System.out.println("上传图片的时间是:"+times);
for (Map.Entry<ReturnImage, Integer> entry : m.entrySet()) {
if(key.getStorageType()==5){
if(config.getDomain()!=null){
jsonArray.add(config.getDomain()+"/links/"+entry.getKey().getImgurl());
img.setImgurl(config.getDomain()+"/links/"+entry.getKey().getImgurl());//图片链接
}else{
jsonArray.add(entry.getKey().getImgurl());
img.setImgurl(entry.getKey().getImgurl());
jsonArray.add(config.getDomain()+"/links/"+entry.getKey().getImgurl());
img.setImgurl("http://"+IPPortUtil.getLocalIP()+":"+IPPortUtil.getLocalPort()+"/links/"+entry.getKey().getImgurl());//图片链接
}
img.setUpdatetime(times);
img.setSource(key.getStorageType());
if (u == null) {
img.setUserid(0);
} else {
img.setUserid(u.getId());
}
img.setSizes((entry.getValue()));
img.setImgname(SetText.getSubString(entry.getKey().getImgurl(), key.getRequestAddress() + "/", ""));
img.setAbnormal(userip);
img.setImgtype(0);
userService.insertimg(img);
long etime = System.currentTimeMillis();
System.out.println("上传图片所用时长:" + String.valueOf(etime - stime) + "ms");
}else{
jsonArray.add(entry.getKey().getImgurl());
img.setImgurl(entry.getKey().getImgurl());
}
img.setUpdatetime(times);
img.setSource(key.getStorageType());
if (u == null) {
img.setUserid(0);
} else {
img.setUserid(u.getId());
}
resultBean = ResultBean.success(jsonArray);
}else{
resultBean = ResultBean.error(-3,"文件类型不符合要求");
img.setSizes((entry.getValue()));
img.setImgname(SetText.getSubString(entry.getKey().getImgurl(), key.getRequestAddress() + "/", ""));
img.setAbnormal(userip);
img.setImgtype(0);
userService.insertimg(img);
long etime = System.currentTimeMillis();
System.out.println("上传图片所用时长:" + String.valueOf(etime - stime) + "ms");
}
resultBean = ResultBean.success(jsonArray);
}else{
resultBean = ResultBean.error(-3,"文件类型不符合要求");
}
}catch (Exception e) {
// TODO: handle exception
Print.warning(e.toString());
resultBean = ResultBean.error(-4,"该文件不支持上传");
}
}else{
resultBean = ResultBean.error(-2,"文件过大");
}catch (Exception e) {
// TODO: handle exception
Print.warning(e.toString());
resultBean = ResultBean.error(-4,"该文件不支持上传");
}
}else{
if(imgsize>0 && imgsize<=(youke*1024*1024)){
try{
boolean bl = ImgUrlUtil.downLoadFromUrl(imgurl,
uuid, request.getSession().getServletContext().getRealPath("/")+"/hellohaotmp/");
if(bl==true){
FileInputStream is = new FileInputStream(request.getSession().getServletContext().getRealPath("/")+"/hellohaotmp/"+uuid);
byte[] b = new byte[3];
is.read(b, 0, b.length);
String xxx = ImgUrlUtil.bytesToHexString(b);
xxx = xxx.toUpperCase();
String ooo = TypeDict.checkType(xxx);
if(is!=null){
is.close();
}
if(!xxx.equals("0000")){
Map<String, String> map = new HashMap<>();
map.put(ooo, request.getSession().getServletContext().getRealPath("/")+"/hellohaotmp/"+uuid);
Map<ReturnImage, Integer> m = null;
if(key.getStorageType()==1){
m = nOSImageupload.Imageupload(null, userpath,map,setday);
}else if (key.getStorageType()==2){
m = ossImageupload.ImageuploadOSS(null, userpath,map,setday);
}else if(key.getStorageType()==3){
m = ussImageupload.ImageuploadUSS(null, userpath,map,setday);
}else if(key.getStorageType()==4){
m = kodoImageupload.ImageuploadKODO(null, userpath,map,setday);
}else if(key.getStorageType()==5){
m =LocUpdateImg.ImageuploadLOC(null,userpath, map,setday);
}else if(key.getStorageType()==6){
m =cosImageupload.ImageuploadCOS(null,userpath, map,setday);
}else if(key.getStorageType()==7){
m = ftpImageupload.ImageuploadFTP(null,userpath,map,setday);
}
else{
System.err.println("未获取到对象存储参数,上传失败。");
}
Images img = new Images();
SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd");
String times = df.format(new Date());
System.out.println("上传图片的时间是:"+times);
for (Map.Entry<ReturnImage, Integer> entry : m.entrySet()) {
if(key.getStorageType()==5){
if(config.getDomain()!=null){
jsonArray.add(config.getDomain()+"/links/"+entry.getKey().getImgurl());
img.setImgurl(config.getDomain()+"/links/"+entry.getKey().getImgurl());//图片链接
}else{
jsonArray.add(config.getDomain()+"/links/"+entry.getKey().getImgurl());
img.setImgurl("http://"+IPPortUtil.getLocalIP()+":"+IPPortUtil.getLocalPort()+"/links/"+entry.getKey().getImgurl());//图片链接
}
}else{
jsonArray.add(entry.getKey().getImgurl());
img.setImgurl(entry.getKey().getImgurl());//图片链接
}
img.setUpdatetime(times);
img.setSource(key.getStorageType());
if (u == null) {
img.setUserid(0);//用户id
} else {
img.setUserid(u.getId());//用户id
}
img.setSizes((entry.getValue()));
img.setImgname(SetText.getSubString(entry.getKey().getImgurl(), key.getRequestAddress() + "/", ""));
img.setAbnormal(userip);
img.setImgtype(0);
userService.insertimg(img);
long etime = System.currentTimeMillis();
System.out.println("上传图片所用时长:" + String.valueOf(etime - stime) + "ms");
}
resultBean = ResultBean.success(jsonArray);
}else{
resultBean = ResultBean.error(-3,"文件类型不符合要求");
}
}
}catch (Exception e) {
// TODO: handle exception
Print.warning(e.toString());
resultBean = ResultBean.error(-4,"文件类型不符合要求");
}
}else{
resultBean = ResultBean.error(-2,"图片太大或不存在");
}
resultBean = ResultBean.error(-2,"文件过大");
}
}else{
resultBean = ResultBean.error(-5,"可用空间不足");
if(imgsize>0 && imgsize<=(youke*1024*1024)){
try{
boolean bl = ImgUrlUtil.downLoadFromUrl(imgurl,
uuid, request.getSession().getServletContext().getRealPath("/")+"/hellohaotmp/");
if(bl==true){
FileInputStream is = new FileInputStream(request.getSession().getServletContext().getRealPath("/")+"/hellohaotmp/"+uuid);
byte[] b = new byte[3];
is.read(b, 0, b.length);
String xxx = ImgUrlUtil.bytesToHexString(b);
xxx = xxx.toUpperCase();
String ooo = TypeDict.checkType(xxx);
if(is!=null){
is.close();
}
if(!xxx.equals("0000")){
Map<String, String> map = new HashMap<>();
map.put(ooo, request.getSession().getServletContext().getRealPath("/")+"/hellohaotmp/"+uuid);
Map<ReturnImage, Integer> m = null;
if(key.getStorageType()==1){
m = nOSImageupload.Imageupload(null, userpath,map,setday);
}else if (key.getStorageType()==2){
m = ossImageupload.ImageuploadOSS(null, userpath,map,setday);
}else if(key.getStorageType()==3 ){
m = ussImageupload.ImageuploadUSS(null, userpath,map,setday);
}else if(key.getStorageType()==4){
m = kodoImageupload.ImageuploadKODO(null, userpath,map,setday);
}else if(key.getStorageType()==5){
m =LocUpdateImg.ImageuploadLOC(null,userpath, map,setday);
}else if(key.getStorageType()==6){
m =cosImageupload.ImageuploadCOS(null,userpath, map,setday);
}else if(key.getStorageType()==7){
m = ftpImageupload.ImageuploadFTP(null,userpath,map,setday);
}else if(key.getStorageType()==8){
m = uFileImageupload.ImageuploadUSS(null, userpath,map,setday);
}
else{
System.err.println("未获取到对象存储参数,上传失败。");
}
Images img = new Images();
SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd");
String times = df.format(new Date());
System.out.println("上传图片的时间是:"+times);
for (Map.Entry<ReturnImage, Integer> entry : m.entrySet()) {
if(key.getStorageType()==5){
if(config.getDomain()!=null){
jsonArray.add(config.getDomain()+"/links/"+entry.getKey().getImgurl());
img.setImgurl(config.getDomain()+"/links/"+entry.getKey().getImgurl());//图片链接
}else{
jsonArray.add(config.getDomain()+"/links/"+entry.getKey().getImgurl());
img.setImgurl("http://"+IPPortUtil.getLocalIP()+":"+IPPortUtil.getLocalPort()+"/links/"+entry.getKey().getImgurl());//图片链接
}
}else{
jsonArray.add(entry.getKey().getImgurl());
img.setImgurl(entry.getKey().getImgurl());//图片链接
}
img.setUpdatetime(times);
img.setSource(key.getStorageType());
if (u == null) {
img.setUserid(0);//用户id
} else {
img.setUserid(u.getId());//用户id
}
img.setSizes((entry.getValue()));
img.setImgname(SetText.getSubString(entry.getKey().getImgurl(), key.getRequestAddress() + "/", ""));
img.setAbnormal(userip);
img.setImgtype(0);
userService.insertimg(img);
long etime = System.currentTimeMillis();
System.out.println("上传图片所用时长:" + String.valueOf(etime - stime) + "ms");
}
resultBean = ResultBean.success(jsonArray);
}else{
resultBean = ResultBean.error(-3,"文件类型不符合要求");
}
}
}catch (Exception e) {
// TODO: handle exception
Print.warning(e.toString());
resultBean = ResultBean.error(-4,"文件类型不符合要求");
}
}else{
resultBean = ResultBean.error(-2,"图片太大或不存在");
}
}
}else{
resultBean = ResultBean.error(-1,"未配置存储源");
resultBean = ResultBean.error(-5,"可用空间不足");
}
}else {resultBean = ResultBean.error(-2, "此用户信息不正确。");}
}else {resultBean = ResultBean.error(-3, "邮箱或密码为空");}
}else{resultBean = ResultBean.error(-4, "管理员关闭了API接口");}
Print.Normal(resultBean.toString());
return resultBean;
/**
* 错误返回值含义:
* -1 存储源key未配置
* -2 目标图片太大或者不存在
* -3 文件类型不符合要求
* */
}
@RequestMapping("/clientlogin")
@@ -470,7 +459,7 @@ Print.Normal(resultBean.toString());
public String login( HttpSession httpSession, String email, String password) {
JSONArray jsonArray = new JSONArray();
String basepass = Base64Encryption.encryptBASE64(password.getBytes());
Integer ret = userService.login(email, basepass);
Integer ret = userService.login(email, basepass,null);
if (ret > 0) {
User user = userService.getUsers(email);
if (user.getIsok() == 1) {
@@ -489,21 +478,39 @@ Print.Normal(resultBean.toString());
@GetMapping (value = "/notices")
@ResponseBody
public String notices() throws Exception {
return "-1";//-1就是没有公告,客户端不显示
}
//主端接口
@PostMapping("/systemupdate")
@ResponseBody
public String sysupdate(String dates) {
Integer i=dates.compareTo(systemupdate);//小于0则需要更新
return i.toString();
}
//主端接口
@PostMapping("/getdomain")
@ResponseBody
public String getdomain(String domain) {
Integer count = domainService.getDomain(domain);
return count.toString();
return "-1";
}
@GetMapping("/getNotice")
@ResponseBody
public Msg getNotice() {
Msg msg = new Msg();
String url = "http://tc.hellohao.cn/getNoticeText";
try {
URL u = new URL("http://tc.hellohao.cn/getNoticeText");
HttpURLConnection uConnection = (HttpURLConnection) u.openConnection();
uConnection.connect();
System.out.println(uConnection.getResponseCode());
if(uConnection.getResponseCode()==200){
if(TestUrl.testUrlWithTimeOut(url,2000)){
String urls =url;
msg.setData(HttpUtil.get(urls));
}else{
msg.setData("暂无公告");
}
}else{
msg.setData("暂无公告");
}
uConnection.disconnect();
} catch (Exception e) {
//e.printStackTrace();
Print.warning("connect failed");
msg.setData("暂无公告");
}
return msg;
}
}
@@ -2,8 +2,10 @@ package cn.hellohao.controller;
import cn.hellohao.exception.StorageSourceInitException;
import cn.hellohao.utils.Print;
import org.springframework.ui.Model;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;
@@ -50,6 +52,20 @@ public class ExceptionHandling {
return e.getMessage();
}
@ExceptionHandler
public String test3(HttpRequestMethodNotSupportedException e,Model model){
ModelAndView modelAndView = new ModelAndView("/index");
Print.Normal("URL访问类型不正确:"+ e.getMessage());
//e.printStackTrace();
modelAndView.addObject("error","URL访问类型不正确。");
model.addAttribute("error","URL访问类型不正确。");
//返回错误信息,并显示给用户
//return e.getMessage();
return "exception";
}
// @ExceptionHandler
// public String methodArgumentNotValid(BindException e) {
@@ -72,19 +72,19 @@ public class GroupController {
@RequestMapping(value = "/addisgroup")
@ResponseBody
public Integer addisgroup(Group group) {
boolean b =false;
if(group.getKeyid()==5){
b =true;
}else{
Keys key = keysService.selectKeys(group.getKeyid());
b = StringUtils.doNull(group.getKeyid(),key);
}
//boolean b =false;
//if(group.getKeyid()==5){
// b =true;
//}else{
//Keys key = keysService.selectKeys(group.getKeyid());
//b = StringUtils.doNull(group.getKeyid(),key);
//}
Integer ret = 0;
if(b){
//if(b){
ret = groupService.addgroup(group);
}else{
ret = -1;
}
//}else{
// ret = -1;
//}
return ret;
}
@RequestMapping(value = "/delegroup")
@@ -4,22 +4,29 @@ import cn.hellohao.pojo.*;
import cn.hellohao.service.*;
import cn.hellohao.service.impl.*;
import cn.hellohao.utils.*;
import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.text.StringEscapeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.FileInputStream;
import java.io.IOException;
import java.awt.image.BufferedImage;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;
@@ -32,8 +39,6 @@ public class UpdateImgController {
@Autowired
private KeysService keysService;
@Autowired
private OSSImageupload ossImageupload;
@Autowired
private ConfigService configService;
@Autowired
private UploadConfigService uploadConfigService;
@@ -47,9 +52,13 @@ public class UpdateImgController {
private FTPImageupload ftpImageupload;
@Autowired
private ImgService imgService;
@Autowired
private UploadServicel uploadServicel;
private String[] iparr;
public static String vu;
@RequestMapping({"/", "/index"})
public String indexImg(Model model, HttpSession httpSession, HttpServletRequest request, HttpServletResponse response) {
Print.Normal("当前项目路径:"+System.getProperty("user.dir"));
@@ -66,7 +75,7 @@ public class UpdateImgController {
if(uploadConfig.getImgcounttourists()!=null){imgcounttourists = uploadConfig.getImgcounttourists();}
if(uploadConfig.getImgcountuser()!=null){imgcountuser = uploadConfig.getImgcountuser();}
if (email != null) {
Integer ret = userService.login(u.getEmail(), u.getPassword());
Integer ret = userService.login(u.getEmail(), u.getPassword(),null);
if (ret > 0) {
User user = userService.getUsers(u.getEmail());
model.addAttribute("username", user.getUsername());
@@ -91,115 +100,22 @@ public class UpdateImgController {
isupdate = (u == null) ? 0: 1;
}
model.addAttribute("VisitorUpload", isupdate);
return "index";
vu = IdUtil.simpleUUID();
model.addAttribute("vu",vu);
if(config.getTheme()==1){
return "index";
}else{
return "index-Minimalism";
}
}
@RequestMapping(value = "/upimg")
@ResponseBody
public String upimg( HttpSession session,HttpServletRequest request
public Msg upimg( HttpSession session,HttpServletRequest request
, @RequestParam(value = "file", required = false) MultipartFile multipartFile,Integer setday,String upurlk) throws Exception {
String userip = GetIPS.getIpAddr(request);
Print.Normal("上传者ip:"+userip);
java.text.DateFormat dateFormat = new java.text.SimpleDateFormat("yyyy/MM/dd");
JSONArray jsonArray = new JSONArray();
JSONObject jsonObject = new JSONObject();
Config config = configService.getSourceype();
UploadConfig uploadConfig = uploadConfigService.getUpdateConfig();
User u = (User) session.getAttribute("user");
Integer usermemory =0;
Integer memory =0;
Integer sourcekey=0;
Integer maxsize = 0;
String userpath = "tourist";
Boolean b =false;
if(uploadConfig.getBlacklist()!=null){
iparr = uploadConfig.getBlacklist().split(";");
for (String s : iparr) {
if(s.equals(userip)){
jsonObject.put("imgurls",911);
return jsonObject.toString();
}
}
}
if(Integer.parseInt(Base64Encryption.decryptBASE64(upurlk))!=yzupdate()){
jsonObject.put("imgurls",403);
return jsonObject.toString();
}
if(u==null){
sourcekey = GetCurrentSource.GetSource(null);
memory = uploadConfig.getVisitormemory();
maxsize = uploadConfig.getFilesizetourists();
usermemory= imgService.getusermemory(0);
if(usermemory==null){usermemory = 0;}
}else{
userpath = u.getUsername();
sourcekey = GetCurrentSource.GetSource(u.getId());
memory = userService.getUsers(u.getEmail()).getMemory();
maxsize = uploadConfig.getFilesizeuser();
usermemory= imgService.getusermemory(u.getId());
if(usermemory==null){usermemory = 0;}
}
if(uploadConfig.getUrltype()==2){
userpath = dateFormat.format(new Date());
}
Keys key = keysService.selectKeys(sourcekey);
if(sourcekey==5){b =true;}
else{b = StringUtils.doNull(sourcekey,key);}
if(!b){
jsonObject.put("imgurls",-1);
return jsonObject.toString();
}
int tmp =(memory==-1? -2:(usermemory/1024));
if(tmp>=memory){
jsonObject.put("imgurls",-5);
return jsonObject.toString();
}
long stime = System.currentTimeMillis();
Map<String, MultipartFile> map = new HashMap<>();
Print.Normal("文件大小:"+multipartFile.getSize());
if(multipartFile.getSize()>maxsize*1024*1024){
jsonObject.put("imgurls",-6);
return jsonObject.toString();
}
String fileName = multipartFile.getOriginalFilename();
String lastname = fileName.substring(fileName.lastIndexOf(".") + 1);
if (!multipartFile.isEmpty()) {
map.put(lastname, multipartFile);
}
Map<ReturnImage, Integer> m = null;
m = GetSource.storageSource(key.getStorageType(),map, userpath,null,setday);
Images img = new Images();
SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd");
Print.Normal("上传图片的时间是:"+df.format(new Date()));
for (Map.Entry<ReturnImage, Integer> entry : m.entrySet()) {
if(key.getStorageType()==5){
if(config.getDomain()!=null){
jsonObject.put("imgurls",config.getDomain()+"/links/"+entry.getKey().getImgurl());
jsonObject.put("imgnames",entry.getKey().getImgname());
img.setImgurl(config.getDomain()+"/links/"+entry.getKey().getImgurl());
}else{
jsonObject.put("imgurls",config.getDomain()+"/links/"+entry.getKey().getImgurl());
jsonObject.put("imgnames",entry.getKey().getImgname());
img.setImgurl("http://"+IPPortUtil.getLocalIP()+":"+IPPortUtil.getLocalPort()+"/links/"+entry.getKey().getImgurl());//图片链接
}
}else{
jsonObject.put("imgurls",entry.getKey().getImgurl());
jsonObject.put("imgnames",entry.getKey().getImgname());
img.setImgurl(entry.getKey().getImgurl());
}
jsonArray.add(jsonObject);
img.setUpdatetime(df.format(new Date()));
img.setSource(key.getStorageType());
img.setUserid(u == null?0:u.getId());
img.setSizes((entry.getValue()) / 1024);
img.setImgname(SetText.getSubString(entry.getKey().getImgurl(), key.getRequestAddress() + "/", ""));
img.setImgtype(setday>0?1:0);
img.setAbnormal(userip);
userService.insertimg(img);
long etime = System.currentTimeMillis();
Print.Normal("上传图片所用时长:" + String.valueOf(etime - stime) + "ms");
}
return jsonObject.toString();
Msg msg = new Msg();
msg = uploadServicel.uploadForLoc(session,request,multipartFile,setday,upurlk,iparr);
return msg;
}
//根据网络图片url上传
@@ -239,7 +155,8 @@ public class UpdateImgController {
java.text.DateFormat dateFormat = new java.text.SimpleDateFormat("yyyy/MM/dd");
userpath = dateFormat.format(new Date());
}
if(Integer.parseInt(Base64Encryption.decryptBASE64(upurlk))!=yzupdate()){
//if(Integer.parseInt(Base64Encryption.decryptBASE64(upurlk))!=yzupdate()){
if (!upurlk.equals(UpdateImgController.vu)) {
jsonArray.add(-403);
return jsonArray.toString();
}
@@ -248,12 +165,12 @@ public class UpdateImgController {
Integer youke = uploadConfig.getFilesizetourists();
Integer yonghu = uploadConfig.getFilesizeuser();
String uuid= UUID.randomUUID().toString().replace("-", "");
Boolean bo =false;
bo = Sourcekey==5?true:StringUtils.doNull(Sourcekey,key);
if(!bo){
jsonArray.add(-1);
return jsonArray.toString();
}
//Boolean bo =false;
//bo = Sourcekey==5?true:StringUtils.doNull(Sourcekey,key);
// if(!bo){
// jsonArray.add(-1);
// return jsonArray.toString();
// }
Print.warning("上传地址是:"+request.getSession().getServletContext().getRealPath("/")+"/hellohaotmp/");
if(usermemory/1024>=memory) {
@@ -268,9 +185,9 @@ public class UpdateImgController {
}
try{
boolean bl =ImgUrlUtil.downLoadFromUrl(imgurl,
uuid, request.getSession().getServletContext().getRealPath("/")+"/hellohaotmp/");
uuid, request.getSession().getServletContext().getRealPath("/")+File.separator+"hellohaotmp"+File.separator);
if(bl==true){
FileInputStream is = new FileInputStream(request.getSession().getServletContext().getRealPath("/")+"/hellohaotmp/"+uuid);
FileInputStream is = new FileInputStream(request.getSession().getServletContext().getRealPath("/")+File.separator+"hellohaotmp"+File.separator+uuid);
byte[] b = new byte[3];
is.read(b, 0, b.length);
String xxx = ImgUrlUtil.bytesToHexString(b);
@@ -281,7 +198,7 @@ public class UpdateImgController {
return jsonArray.toString();
}
Map<String, String> map = new HashMap<>();
map.put(TypeDict.checkType(xxx), request.getSession().getServletContext().getRealPath("/")+"/hellohaotmp/"+uuid);
map.put(TypeDict.checkType(xxx), request.getSession().getServletContext().getRealPath("/")+"hellohaotmp"+ File.separator+uuid);
Map<ReturnImage, Integer> m = null;
m = GetSource.storageSource(key.getStorageType(), null, userpath,map,setday);
Images img = new Images();
@@ -291,11 +208,11 @@ public class UpdateImgController {
for (Map.Entry<ReturnImage, Integer> entry : m.entrySet()) {
if(key.getStorageType()==5){
if(config.getDomain()!=null){
jsonArray.add(config.getDomain()+"/links/"+entry.getKey().getImgurl());
img.setImgurl(config.getDomain()+"/links/"+entry.getKey().getImgurl());//图片链接
jsonArray.add(config.getDomain()+"/"+entry.getKey().getImgurl());
img.setImgurl(config.getDomain()+"/"+entry.getKey().getImgurl());//图片链接
}else{
jsonArray.add(config.getDomain()+"/links/"+entry.getKey().getImgurl());
img.setImgurl("http://"+IPPortUtil.getLocalIP()+":"+IPPortUtil.getLocalPort()+"/links/"+entry.getKey().getImgurl());//图片链接
jsonArray.add(config.getDomain()+"/"+entry.getKey().getImgurl());
img.setImgurl("http://"+IPPortUtil.getLocalIP()+":"+IPPortUtil.getLocalPort()+"/"+entry.getKey().getImgurl());//图片链接
}
}else{
jsonArray.add(entry.getKey().getImgurl());
@@ -305,7 +222,8 @@ public class UpdateImgController {
img.setSource(key.getStorageType());
img.setUserid(u == null?0:u.getId());
img.setSizes((entry.getValue()));
img.setImgname(SetText.getSubString(entry.getKey().getImgurl(), key.getRequestAddress() + "/", ""));
//img.setImgname(SetText.getSubString(entry.getKey().getImgurl(), key.getRequestAddress() + "/", ""));
img.setImgname(entry.getKey().getImgurl());
img.setAbnormal(userip);
if(setday>0){img.setImgtype(1);}
else{img.setImgtype(0);}
@@ -326,9 +244,9 @@ public class UpdateImgController {
}
try{
boolean bl = ImgUrlUtil.downLoadFromUrl(imgurl,
uuid, request.getSession().getServletContext().getRealPath("/")+"/hellohaotmp/");
uuid, request.getSession().getServletContext().getRealPath("/")+"hellohaotmp"+File.separator);
if(bl==true){
FileInputStream is = new FileInputStream(request.getSession().getServletContext().getRealPath("/")+"/hellohaotmp/"+uuid);
FileInputStream is = new FileInputStream(request.getSession().getServletContext().getRealPath("/")+"hellohaotmp"+File.separator+uuid);
byte[] b = new byte[3];
is.read(b, 0, b.length);
String xxx = ImgUrlUtil.bytesToHexString(b);
@@ -339,7 +257,7 @@ public class UpdateImgController {
return jsonArray.toString();
}
Map<String, String> map = new HashMap<>();
map.put(TypeDict.checkType(xxx), request.getSession().getServletContext().getRealPath("/")+"/hellohaotmp/"+uuid);
map.put(TypeDict.checkType(xxx), request.getSession().getServletContext().getRealPath("/")+File.separator+"hellohaotmp"+File.separator+uuid);
Map<ReturnImage, Integer> m = null;
m = GetSource.storageSource(key.getStorageType(), null, userpath,map,setday);
Images img = new Images();
@@ -349,11 +267,11 @@ public class UpdateImgController {
for (Map.Entry<ReturnImage, Integer> entry : m.entrySet()) {
if(key.getStorageType()==5){
if(config.getDomain()!=null){
jsonArray.add(config.getDomain()+"/links/"+entry.getKey().getImgurl());
img.setImgurl(config.getDomain()+"/links/"+entry.getKey().getImgurl());
jsonArray.add(config.getDomain()+"/"+entry.getKey().getImgurl());
img.setImgurl(config.getDomain()+"/"+entry.getKey().getImgurl());
}else{
jsonArray.add(config.getDomain()+"/links/"+entry.getKey().getImgurl());
img.setImgurl("http://"+IPPortUtil.getLocalIP()+":"+IPPortUtil.getLocalPort()+"/links/"+entry.getKey().getImgurl());//图片链接
jsonArray.add(config.getDomain()+"/"+entry.getKey().getImgurl());
img.setImgurl("http://"+IPPortUtil.getLocalIP()+":"+IPPortUtil.getLocalPort()+"/"+entry.getKey().getImgurl());//图片链接
}
}else{
jsonArray.add(entry.getKey().getImgurl());
@@ -419,6 +337,128 @@ public class UpdateImgController {
}
@RequestMapping("/{key1}/TOIMG{key2}N.{key3}")
public ResponseEntity<Object> selectByFyOne(final HttpServletRequest request,
HttpServletResponse response,
@PathVariable("key1") String key1, @PathVariable("key2") String key2,
@PathVariable("key3") String key3, Model model){
MediaType mediaType =null;
File file = new File(File.separator+"HellohaoData"+File.separator+key1+"/TOIMG"+key2+"N."+key3);
if (!file.exists()) {
try {
response.sendRedirect("/404");
} catch (IOException e) {
e.printStackTrace();
return ResponseEntity.status(HttpStatus.NOT_FOUND).body("<h1>404 FILE NOT FOUND</h1>");
}
}
if(key3.equals("png")){
mediaType = MediaType.IMAGE_PNG;
}else if(key3.equals("gif")){
mediaType = MediaType.IMAGE_GIF;
}else{
mediaType = MediaType.IMAGE_JPEG;
}
HttpHeaders headers = new HttpHeaders();
headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
// headers.setContentDispositionFormData("attachment", URLUtil.encode(file.getName()));
headers.add("Pragma", "no-cache");
headers.add("Expires", "0");
headers.add("Last-Modified", new Date().toString());
headers.add("ETag", String.valueOf(System.currentTimeMillis()));
return ResponseEntity
.ok()
.headers(headers)
.contentLength(file.length())
.contentType(mediaType)
.body(new FileSystemResource(file));
//return "forward:/links/"+key1+"/TOIMG"+key2+"N."+key3;
}
// @RequestMapping("/{key1:\\d+}/{key2}/{key3}/TOIMG{key4}N.{key5}")
public void selectByFy2(HttpServletRequest request, HttpServletResponse response,
@PathVariable("key1") String key1,@PathVariable("key2") String key2,
@PathVariable("key3") String key3,@PathVariable("key4") String key4,
@PathVariable("key5") String key5,Model model) {
String head = "jpg";
if(key5.equals("jpg")||key5.equals("jpeg")){
head = "jpeg";
}else if(key5.equals("png")){
head = "png";
}else if(key5.equals("bmp")){
head = "bmp";
}else if(key5.equals("gif")){
head = "gif";
}else{
head = key5;
}
response.setHeader("Pragma", "no-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
response.setContentType("image/"+head);
//InputStream is= null;
BufferedImage bi=null;
try {
//is = new FileInputStream(new File(File.separator+"HellohaoData"+File.separator+key1+"/"+key2+"/"+key3+"/TOIMG"+key4+"N."+key5));
bi= ImageIO.read(new File(File.separator+"HellohaoData"+File.separator+key1+"/"+key2+"/"+key3+"/TOIMG"+key4+"N."+key5));
//is.close();
//将图片输出给浏览器
BufferedImage image = (bi) ;
OutputStream os = response.getOutputStream();
ImageIO.write(image, head, os);
} catch (Exception e) {
Print.warning("寻找本地文件出错:"+e.getMessage());
e.printStackTrace();
try {
response.sendRedirect("/404");
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
@GetMapping("/{key1:\\d+}/{key2}/{key3}/TOIMG{key4}N.{key5}")
@ResponseBody
public ResponseEntity<Object> selectByFyTow(final HttpServletRequest request,
HttpServletResponse response,
@PathVariable("key1") String key1,
@PathVariable("key2") String key2,
@PathVariable("key3") String key3,
@PathVariable("key4") String key4,
@PathVariable("key5") String key5) {
MediaType mediaType =null;
File file = new File(File.separator+"HellohaoData"+File.separator+key1+"/"+key2+"/"+key3+"/TOIMG"+key4+"N."+key5);
if (!file.exists()) {
try {
response.sendRedirect("/404");
} catch (IOException e) {
e.printStackTrace();
return ResponseEntity.status(HttpStatus.NOT_FOUND).body("<h1>404 FILE NOT FOUND</h1>");
}
}
if(key5.equals("png")){
mediaType = MediaType.IMAGE_PNG;
}else if(key5.equals("gif")){
mediaType = MediaType.IMAGE_GIF;
}else{
mediaType = MediaType.IMAGE_JPEG;
}
HttpHeaders headers = new HttpHeaders();
headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
// headers.setContentDispositionFormData("attachment", URLUtil.encode(file.getName()));
headers.add("Pragma", "no-cache");
headers.add("Expires", "0");
headers.add("Last-Modified", new Date().toString());
headers.add("ETag", String.valueOf(System.currentTimeMillis()));
return ResponseEntity
.ok()
.headers(headers)
.contentLength(file.length())
.contentType(mediaType)
.body(new FileSystemResource(file));
}
private Integer yzupdate(){
Calendar cal = Calendar.getInstance();
int y=cal.get(Calendar.YEAR);
@@ -434,4 +474,5 @@ public class UpdateImgController {
return "err";
}
}
@@ -1,5 +1,6 @@
package cn.hellohao.controller;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
@@ -7,7 +8,9 @@ import java.util.Random;
import java.util.UUID;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
@@ -108,16 +111,20 @@ public class UserController {
@RequestMapping("/login")
@ResponseBody
public String login( HttpSession httpSession, String email, String password,Integer logotmp) {
public String login( HttpServletResponse response,HttpSession httpSession, String email, String password,Integer logotmp) {
JSONArray jsonArray = new JSONArray();
if((logotmp-number1)==(istmp1-number1)){
String basepass = Base64Encryption.encryptBASE64(password.getBytes());
Integer ret = userService.login(email, basepass);
Integer ret = userService.login(email, basepass,null);
if (ret > 0) {
User user = userService.getUsers(email);
if (user.getIsok() == 1) {
httpSession.setAttribute("user", user);
httpSession.setAttribute("email", user.getEmail());
Cookie cookie = new Cookie("Hellohao_UniqueUserKey", userService.getUsers(user.getEmail()).getUid());
cookie.setMaxAge(60*60*24*90);
cookie.setPath("/");
response.addCookie(cookie);
jsonArray.add(1);
} else if(ret==-1){
jsonArray.add(-1);
@@ -133,11 +140,48 @@ public class UserController {
return jsonArray.toString();
}
@RequestMapping("/login_c")
@ResponseBody
public String login( HttpSession httpSession, String Hellohao_UniqueUserKey) {
JSONArray jsonArray = new JSONArray();
Integer ret = userService.login(null, null,Hellohao_UniqueUserKey);
if (ret > 0) {
User user = userService.getUsersMail(Hellohao_UniqueUserKey);
if (user.getIsok() == 1) {
httpSession.setAttribute("user", user);
httpSession.setAttribute("email", user.getEmail());
jsonArray.add(1);
} else if(ret==-1){
jsonArray.add(-1);
}else {
jsonArray.add(-2);
}
} else {
jsonArray.add(0);
}
return jsonArray.toString();
}
//退出
@RequestMapping(value = "/exit.do")
@ResponseBody
public String exit(Model model, HttpServletRequest request, HttpSession session) {
public String exit(Model model, HttpServletRequest request, HttpServletResponse response, HttpSession session) {
JSONObject jsonObject = new JSONObject();
Cookie[] cookies = request.getCookies();
if(cookies!=null){
for (Cookie cookie : cookies) {
Cookie c = null;
cookie.setPath("/");
if(cookie.getName().equals("Hellohao_UniqueUserKey")){
//cookie.setValue(null);
c = new Cookie("Hellohao_UniqueUserKey","");
c.setPath("/");
cookie.setMaxAge(0);//60*60*24*90
response.addCookie(c);
}
}
}
//注销,移除session
User user = (User) session.getAttribute("user");
if (user.getEmail() != null && user.getPassword() != null) {
@@ -0,0 +1,25 @@
package cn.hellohao.dao;
import cn.hellohao.pojo.Album;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import javax.validation.constraints.Max;
import java.util.List;
/**
* @author Hellohao
* @version 1.0
* @date 2019-12-18 22:15
*/
@Mapper
public interface AlbumMapper {
Album selectAlbum(Album album);
Integer addAlbum(Album album);
Integer deleteAlbum(@Param("albumkey") String albumkey);
List<Album> selectAlbumURLList(Album album);
}
@@ -1,16 +0,0 @@
package cn.hellohao.dao;
import cn.hellohao.pojo.Domain;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
/**
* @author Hellohao
* @version 1.0
* @date 2019/8/21 9:46
*/
@Mapper
public interface DomainMapper {
Integer getDomain(@Param("domain") String domain);
}
@@ -0,0 +1,26 @@
package cn.hellohao.dao;
import cn.hellohao.pojo.Images;
import cn.hellohao.pojo.ImgAndAlbum;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.util.List;
/**
* @author Hellohao
* @version 1.0
* @date 2019-12-18 22:15
*/
@Mapper
public interface ImgAndAlbumMapper {
Integer addImgAndAlbum(ImgAndAlbum imgAndAlbum);
List<ImgAndAlbum> getAlbumForImgname(@Param("imgname") String imgname);
Integer deleteImgAndAlbum(@Param("imgname") String imgname);
Integer deleteImgAndAlbumForKey(@Param("albumkey") String albumkey);
List<Images> selectImgForAlbumkey(@Param("albumkey") String albumkey);
}
+7 -1
View File
@@ -20,7 +20,7 @@ public interface ImgMapper {
Integer counts(@Param("userid") Integer userid);
Integer setabnormal(@Param("imgname") String imgname,@Param("abnormal") String abnormal);
Integer setImg(Images images);
Integer deleimgname(@Param("imgname") String imgname);
Integer deleall(@Param("id") Integer id);
@@ -28,4 +28,10 @@ public interface ImgMapper {
List<Images> gettimeimg(@Param("time") String time);
Integer getusermemory(@Param("userid") Integer userid);
Integer md5Count(@Param("md5key") String md5key);
Images selectImgUrlByMD5(@Param("md5key") String md5key);
}
@@ -14,7 +14,7 @@ public interface UserMapper {
Integer register(User user);
//登录
Integer login(@Param("email") String email, @Param("password") String password);
Integer login(@Param("email") String email, @Param("password") String password,@Param("uid") String uid);
//获取用户信息
User getUsers(@Param("email") String email);
@@ -1,13 +1,20 @@
package cn.hellohao.interceptor;
import java.io.PrintWriter;
import java.net.URLDecoder;
import java.net.URLEncoder;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import cn.hellohao.pojo.User;
import cn.hellohao.service.impl.NOSImageupload;
import cn.hellohao.service.impl.UserServiceImpl;
import cn.hellohao.utils.Base64Encryption;
import cn.hellohao.utils.Print;
import cn.hellohao.utils.SpringContextHolder;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
@@ -25,17 +32,40 @@ public class InterceptorConfig implements HandlerInterceptor {
*/
//这个方法是在访问接口之前执行的,我们只需要在这里写验证登陆状态的业务逻辑,就可以在用户调用指定接口之前验证登陆状态了
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
UserServiceImpl userService = SpringContextHolder.getBean(UserServiceImpl.class);
HttpSession session = request.getSession();
//这里的User是登陆时放入session的
User user = (User) session.getAttribute("user");
//这里的User是登陆时放入session的
// User user = (User) session.getAttribute("user");
// if(user==null){
// Cookie[] cookies = request.getCookies();
// String Hellohao_UniqueUserKey = "";
// for (Cookie cookie : cookies) {
// if(cookie.getName().equals("Hellohao_UniqueUserKey") && Hellohao_UniqueUserKey.equals("")){
// Hellohao_UniqueUserKey = URLDecoder.decode(cookie.getValue(), "GBK");
// }
// }
//
// if(Hellohao_UniqueUserKey!=null && !Hellohao_UniqueUserKey.equals("")){
// //String basepass = Base64Encryption.encryptBASE64(pass.getBytes());
// Integer ret = userService.login(null, null,Hellohao_UniqueUserKey);
// if (ret > 0) {
// User u = userService.getUsersMail(Hellohao_UniqueUserKey);
// if (u.getIsok() == 1) {
// session.setAttribute("user", u);
// session.setAttribute("email", u.getEmail());
// //request.getRequestDispatcher("/admin/goadmin").forward(request, response);
// }
// }
// }
//
// }
User suser = (User) session.getAttribute("user");
String email = null;
Integer level = 0;
if (user != null) {
email = user.getEmail();
level = user.getLevel();
if (suser != null) {
email = suser.getEmail();
level = suser.getLevel();
}
// String email = (String) session.getAttribute("email");
//如果session中没有user,表示没登陆
if (email == null) {
//这个方法返回false表示忽略当前请求,如果一个用户调用了需要登陆才能使用的接口,如果他没有登陆这里会直接忽略掉
//当然你可以利用response给用户返回一些提示信息,告诉他没登陆
@@ -43,7 +73,6 @@ public class InterceptorConfig implements HandlerInterceptor {
request.getRequestDispatcher("/err").forward(request, response);
return false;
} else {
//System.out.println("进入成功");
return true; //如果session里有user,表示该用户已经登陆,放行,用户即可继续调用自己需要的接口
}
@@ -18,6 +18,8 @@ public class WebAppConfig implements WebMvcConfigurer {
private InterceptorConfig interceptorConfig;
@Autowired
private InterceptorConfigTwo interceptorConfigTwo;
@Autowired
private InterceptorConfigWeb interceptorConfigWeb;
// 这个方法是用来配置静态资源的,比如html,js,css,等等
@@ -31,8 +33,13 @@ public class WebAppConfig implements WebMvcConfigurer {
// addPathPatterns("/**") 表示拦截所有的请求,
// excludePathPatterns("/login", "/register") 表示除了登陆与注册之外,因为登陆注册不需要登陆也可以访问
//registry.addInterceptor(interceptorConfig).addPathPatterns("admin/**").excludePathPatterns("/login", "/register");
registry.addInterceptor(interceptorConfig).addPathPatterns("/admin/**");
registry.addInterceptor(interceptorConfigTwo).addPathPatterns("/admin/root/**");
registry.addInterceptor(interceptorConfigWeb).addPathPatterns("/**")
.excludePathPatterns("/static/**","/**/*.css", "/**/*.js", "/**/*.png", "/**/*.jpg",
"/**/*.jpeg", "/**/*.gif", "/**/fonts/*", "/**/*.svg","/**/*.*",
"/clientupimg/**","/clientupurlimg/**","/clientlogin/**","/notices/**","/systemupdate/**","/getdomain/**",
"/getNoticeText/**","/getNotice/**","/addalbum/**","/addalbum/**","/SaveForAlbum/**","/TOALBUM*N/**","/TOALBUM*N/**");
registry.addInterceptor(interceptorConfig).addPathPatterns("/admin/**").excludePathPatterns("/**/*.*");
registry.addInterceptor(interceptorConfigTwo).addPathPatterns("/admin/root/**").excludePathPatterns("/**/*.*");
+75
View File
@@ -0,0 +1,75 @@
package cn.hellohao.pojo;
/**
* @author Hellohao
* @version 1.0
* @date 2019-12-18 22:13
*/
public class Album {
private String albumkey;
private String albumtitle;
private String createdate;
private String password;
private Integer userid;
private String username;
public Album() {
}
public Album(String albumkey, String albumtitle, String createdate, String password, Integer userid, String username) {
this.albumkey = albumkey;
this.albumtitle = albumtitle;
this.createdate = createdate;
this.password = password;
this.userid = userid;
this.username = username;
}
public String getAlbumkey() {
return albumkey;
}
public void setAlbumkey(String albumkey) {
this.albumkey = albumkey;
}
public String getAlbumtitle() {
return albumtitle;
}
public void setAlbumtitle(String albumtitle) {
this.albumtitle = albumtitle;
}
public String getCreatedate() {
return createdate;
}
public void setCreatedate(String createdate) {
this.createdate = createdate;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Integer getUserid() {
return userid;
}
public void setUserid(Integer userid) {
this.userid = userid;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
}
+11 -1
View File
@@ -18,11 +18,12 @@ public class Config {
private String webms;
private String webkeywords;
private String webfavicons;
private Integer theme;
public Config() {
}
public Config(Integer id, Integer sourcekey, Integer emails, String webname, String explain, String video, Integer backtype, String links, String notice, String baidu, String domain, String background1, String background2, String sett, String webms, String webkeywords, String webfavicons) {
public Config(Integer id, Integer sourcekey, Integer emails, String webname, String explain, String video, Integer backtype, String links, String notice, String baidu, String domain, String background1, String background2, String sett, String webms, String webkeywords, String webfavicons, Integer theme) {
this.id = id;
this.sourcekey = sourcekey;
this.emails = emails;
@@ -40,6 +41,7 @@ public class Config {
this.webms = webms;
this.webkeywords = webkeywords;
this.webfavicons = webfavicons;
this.theme = theme;
}
public Integer getId() {
@@ -177,4 +179,12 @@ public class Config {
public void setWebfavicons(String webfavicons) {
this.webfavicons = webfavicons;
}
public Integer getTheme() {
return theme;
}
public void setTheme(Integer theme) {
this.theme = theme;
}
}
+69 -2
View File
@@ -2,6 +2,9 @@ package cn.hellohao.pojo;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.hibernate.validator.constraints.Length;
import javax.validation.constraints.NotBlank;
public class Images {
// 默认的时间字符串格式
@@ -20,13 +23,23 @@ public class Images {
private Integer storageType;
private String starttime;
private String stoptime;
@Length(min = 1, max = 100, message = "图片描述不得超过100个字符")
private String explains;
private String md5key;
//Album
@NotBlank(message = "画廊标题不能为空")
@Length(min = 1, max = 50, message = "画廊标题不得超过50个字符")
private String albumtitle;
@Length(min = 0, max = 10, message = "画廊密码不能超过10个字符")
private String password;
private Integer selecttype;
private String notes;
public Images() {
super();
}
public Images(Integer id, String imgname, String imgurl, Integer userid, Integer sizes, String abnormal, Integer source, Integer imgtype, String updatetime, String username, Integer storageType, String starttime, String stoptime) {
public Images(Integer id, String imgname, String imgurl, Integer userid, Integer sizes, String abnormal, Integer source, Integer imgtype, String updatetime, String username, Integer storageType, String starttime, String stoptime, @Length(min = 1, max = 100, message = "图片描述不得超过100个字符") String explains, String md5key, String albumtitle,String password, Integer selecttype, String notes) {
this.id = id;
this.imgname = imgname;
this.imgurl = imgurl;
@@ -40,6 +53,12 @@ public class Images {
this.storageType = storageType;
this.starttime = starttime;
this.stoptime = stoptime;
this.explains = explains;
this.md5key = md5key;
this.albumtitle = albumtitle;
this.password = password;
this.selecttype = selecttype;
this.notes = notes;
}
public Integer getId() {
@@ -145,6 +164,54 @@ public class Images {
public void setStoptime(String stoptime) {
this.stoptime = stoptime;
}
public String getExplains() {
return explains;
}
public void setExplains(String explains) {
this.explains = explains;
}
public String getMd5key() {
return md5key;
}
public void setMd5key(String md5key) {
this.md5key = md5key;
}
public String getAlbumtitle() {
return albumtitle;
}
public void setAlbumtitle(String albumtitle) {
this.albumtitle = albumtitle;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Integer getSelecttype() {
return selecttype;
}
public void setSelecttype(Integer selecttype) {
this.selecttype = selecttype;
}
public String getNotes() {
return notes;
}
public void setNotes(String notes) {
this.notes = notes;
}
}
@@ -0,0 +1,45 @@
package cn.hellohao.pojo;
/**
* @author Hellohao
* @version 1.0
* @date 2019-12-18 22:12
*/
public class ImgAndAlbum {
private String imgname;
private String albumkey;
private String notes;
public ImgAndAlbum() {
}
public ImgAndAlbum(String imgname, String albumkey, String notes) {
this.imgname = imgname;
this.albumkey = albumkey;
this.notes = notes;
}
public String getImgname() {
return imgname;
}
public void setImgname(String imgname) {
this.imgname = imgname;
}
public String getAlbumkey() {
return albumkey;
}
public void setAlbumkey(String albumkey) {
this.albumkey = albumkey;
}
public String getNotes() {
return notes;
}
public void setNotes(String notes) {
this.notes = notes;
}
}
+112
View File
@@ -0,0 +1,112 @@
package cn.hellohao.pojo;
import java.io.Serializable;
/**
* 交互消息,默认成功
* @author Hellohao
*
*/
public class Msg implements Serializable {
private static final long serialVersionUID = 5196249482551119279L;
//返回码
private String code ="200";
//提示信息
private String info="操作成功";
//返回数据
private Object data;
//异常
private String exceptions;
public Msg() {}
public void set(String code, String info){
this.code = code;
this.info = info;
}
/**
* 默认成功操作
* @param data
*/
public Msg(Object data) {
super();
this.data = data;
}
public Msg(String code, String info) {
super();
this.code = code;
this.info = info;
}
public Msg(String code, String info, Object data) {
super();
this.code = code;
this.info = info;
this.data = data;
}
public Msg(String code, String info, Object data, String exceptions) {
super();
this.code = code;
this.info = info;
this.data = data;
this.exceptions = exceptions;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getInfo() {
return info;
}
public void setInfo(String info) {
this.info = info;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
public String getExceptions() {
return exceptions;
}
public void setExceptions(String exceptions) {
this.exceptions = exceptions;
}
@Override
public String toString() {
return "Msg [code=" + code + ", info=" + info + ", data=" + data
+ ", exceptions=" + exceptions + "]";
}
}
@@ -6,7 +6,9 @@ import cn.hellohao.pojo.Keys;
import cn.hellohao.service.impl.ImgServiceImpl;
import cn.hellohao.service.impl.ImgreviewServiceImpl;
import cn.hellohao.service.impl.KeysServiceImpl;
import cn.hellohao.service.impl.NOSImageupload;
import cn.hellohao.utils.LocUpdateImg;
import cn.hellohao.utils.SpringContextHolder;
import com.alibaba.fastjson.JSON;
import com.baidu.aip.contentcensor.AipContentCensor;
import com.baidu.aip.contentcensor.EImgType;
@@ -90,25 +92,28 @@ public class SchedulerTask {
schedulerTask.imgreviewService.updateByPrimaryKeySelective(imgreview1);
Keys key =null;
if(images.getSource()==1){
key = keysService.selectKeys(images.getSource());
key =schedulerTask.keysService.selectKeys(images.getSource());
schedulerTask.imgService.delect(key, images.getImgname());
}else if (images.getSource()==2){
key = keysService.selectKeys(images.getSource());
key = schedulerTask.keysService.selectKeys(images.getSource());
schedulerTask.imgService.delectOSS(key, images.getImgname());
}else if(images.getSource()==3){
key = keysService.selectKeys(images.getSource());
key = schedulerTask.keysService.selectKeys(images.getSource());
schedulerTask.imgService.delectUSS(key, images.getImgname());
}else if(images.getSource()==4){
key = keysService.selectKeys(images.getSource());
key = schedulerTask.keysService.selectKeys(images.getSource());
schedulerTask.imgService.delectKODO(key, images.getImgname());
}else if(images.getSource()==5){
LocUpdateImg.deleteLOCImg(images.getImgname());
}else if(images.getSource()==6){
key = keysService.selectKeys(images.getSource());
key = schedulerTask.keysService.selectKeys(images.getSource());
schedulerTask.imgService.delectCOS(key, images.getImgname());
}else if(images.getSource()==7){
key = keysService.selectKeys(images.getSource());
key = schedulerTask.keysService.selectKeys(images.getSource());
schedulerTask.imgService.delectFTP(key, images.getImgname());
}else if(images.getSource()==8){
key = schedulerTask.keysService.selectKeys(images.getSource());
schedulerTask.imgService.delectUFile(key, images.getImgname());
}else{
System.err.println("未获取到对象存储参数,上传失败。");
}
@@ -1,5 +1,6 @@
package cn.hellohao.quartz;
import cn.hellohao.pojo.FixedResources;
import cn.hellohao.pojo.Keys;
import cn.hellohao.service.impl.ImgServiceImpl;
import cn.hellohao.service.impl.KeysServiceImpl;
@@ -42,6 +43,10 @@ public class TempImgTask {
public void start() throws InterruptedException {
File f = new File(FixedResources.LOCPATH);
if (!f.exists()) {
f.mkdirs();
}
List<String> list = new ArrayList<>();
File file = new File(File.separator + "HellohaoData"+File.separator+"img.ini");
//判断文件是否存在
@@ -52,7 +57,6 @@ public class TempImgTask {
String s = null;
while ((s = br.readLine()) != null) {//使用readLine方法,一次读一行
result.append(System.lineSeparator() + s);
//Print.Normal( s);
String str = s;
String[] strArr = str.split("\\|");
System.out.println(strArr.length); //这里输出3
@@ -0,0 +1,24 @@
package cn.hellohao.service;
import cn.hellohao.pojo.Album;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* @author Hellohao
* @version 1.0
* @date 2019-12-18 22:15
*/
@Service
public interface AlbumService {
Album selectAlbum(Album album);
Integer addAlbum(Album album);
Integer deleteAlbum(String albumkey);
List<Album> selectAlbumURLList(Album album);
}
@@ -1,14 +0,0 @@
package cn.hellohao.service;
import cn.hellohao.pojo.Domain;
import org.springframework.stereotype.Service;
/**
* @author Hellohao
* @version 1.0
* @date 2019/8/21 9:50
*/
@Service
public interface DomainService {
Integer getDomain(String domain);
}
@@ -0,0 +1,25 @@
package cn.hellohao.service;
import cn.hellohao.pojo.Images;
import cn.hellohao.pojo.ImgAndAlbum;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* @author Hellohao
* @version 1.0
* @date 2019-12-18 22:29
*/
@Service
public interface ImgAndAlbumService {
Integer addImgAndAlbum(ImgAndAlbum imgAndAlbum);
List<ImgAndAlbum> getAlbumForImgname(String imgname);
Integer deleteImgAndAlbum(String imgname);
Integer deleteImgAndAlbumForKey(String albumkey);
List<Images> selectImgForAlbumkey(String albumkey);
}
@@ -6,7 +6,9 @@ import java.util.List;
import org.apache.ibatis.annotations.Param;
import cn.hellohao.pojo.Images;
import org.springframework.stereotype.Service;
@Service
public interface ImgService {
List<Images> selectimg(Images images);
@@ -18,7 +20,7 @@ public interface ImgService {
Integer counts(Integer userid);
Integer setabnormal(String imgname,String abnormal);
Integer setImg(Images images);
Integer deleimgname(String imgname);
@@ -27,4 +29,9 @@ public interface ImgService {
List<Images> gettimeimg(String time);
Integer getusermemory(Integer userid);
Integer md5Count(String md5key);
Images selectImgUrlByMD5(String md5key);
}
@@ -1,7 +1,9 @@
package cn.hellohao.service;
import cn.hellohao.pojo.Imgreview;
import org.springframework.stereotype.Service;
@Service
public interface ImgreviewService {
int deleteByPrimaryKey(Integer id);
@@ -2,9 +2,11 @@ package cn.hellohao.service;
import cn.hellohao.pojo.Keys;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public interface KeysService {
//查询密钥
Keys selectKeys(Integer storageType);
@@ -1,5 +1,8 @@
package cn.hellohao.service;
import org.springframework.stereotype.Service;
@Service
public interface NoticeService {
String getNotice();
@@ -3,15 +3,17 @@ package cn.hellohao.service;
import cn.hellohao.pojo.Images;
import cn.hellohao.pojo.User;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public interface UserService {
//注册
Integer register(User user);
//登录
Integer login(String email, String password);
Integer login(String email, String password,String uid);
//获取用户信息
User getUsers(String email);
@@ -0,0 +1,89 @@
package cn.hellohao.service.impl;
import cn.hellohao.dao.AlbumMapper;
import cn.hellohao.dao.ConfigMapper;
import cn.hellohao.dao.ImgAndAlbumMapper;
import cn.hellohao.exception.CodeException;
import cn.hellohao.pojo.Album;
import cn.hellohao.pojo.ImgAndAlbum;
import cn.hellohao.pojo.Msg;
import cn.hellohao.service.AlbumService;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.UUID;
/**
* @author Hellohao
* @version 1.0
* @date 2019-12-18 22:30
*/
@Service
public class AlbumServiceI implements AlbumService {
@Autowired
AlbumMapper albumMapper;
@Autowired
ImgAndAlbumMapper andAlbumMapper;
@Autowired
ConfigMapper configMapper;
@Override
public Album selectAlbum(Album album) {
return albumMapper.selectAlbum(album);
}
@Override
public Integer addAlbum(Album album) {
return albumMapper.addAlbum(album);
}
@Transactional
public Integer addAlbumForImgAndAlbumMapper(ImgAndAlbum imgAndAlbum) {
Integer tem = 0;
Integer r2 = andAlbumMapper.addImgAndAlbum(imgAndAlbum);
if(r2>0){
tem = 1;
}else{
throw new CodeException("插入画廊数据失败,回滚");
}
return tem;
}
@Override
public Integer deleteAlbum(String albumkey) {
return albumMapper.deleteAlbum(albumkey);
}
@Override
public List<Album> selectAlbumURLList(Album album) {
return albumMapper.selectAlbumURLList(album);
}
@Transactional
public Integer delete(String albumkey) {
Integer ret1 = albumMapper.deleteAlbum(albumkey);
if(ret1>0){
ret1 = andAlbumMapper.deleteImgAndAlbumForKey(albumkey);
}else{
throw new CodeException("删除画廊失败。");
}
return ret1;
}
@Transactional
public Integer deleteAll(String[] albumkeyArr) {
Integer ret1 = 0 ;
for (String s : albumkeyArr) {
ret1 = albumMapper.deleteAlbum(s);
if(ret1>0){
ret1 = andAlbumMapper.deleteImgAndAlbumForKey(s);
}else{
throw new CodeException("删除画廊失败。");
}
}
return ret1;
}
}
@@ -3,10 +3,7 @@ package cn.hellohao.service.impl;
import cn.hellohao.pojo.Keys;
import cn.hellohao.pojo.ReturnImage;
import cn.hellohao.pojo.UploadConfig;
import cn.hellohao.utils.DateUtils;
import cn.hellohao.utils.DeleImg;
import cn.hellohao.utils.ImgUrlUtil;
import cn.hellohao.utils.Print;
import cn.hellohao.utils.*;
import com.netease.cloud.auth.BasicCredentials;
import com.netease.cloud.auth.Credentials;
import com.netease.cloud.services.nos.NosClient;
@@ -18,9 +15,7 @@ import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.exception.CosClientException;
import com.qcloud.cos.exception.CosServiceException;
import com.qcloud.cos.model.Bucket;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.model.*;
import com.qcloud.cos.region.Region;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
@@ -36,94 +31,91 @@ public class COSImageupload {
static Keys key;
public Map<ReturnImage, Integer> ImageuploadCOS(Map<String, MultipartFile> fileMap, String username,
Map<String, String> fileMap2,Integer setday) throws Exception {
Map<String, String> fileMap2,Integer setday) {
// 要上传文件的路径
if(fileMap2==null){
File file = null;
Map<ReturnImage, Integer> ImgUrl = new HashMap<>();
for (Map.Entry<String, MultipartFile> entry : fileMap.entrySet()) {
String uuid = UUID.randomUUID().toString().replace("-", "").toLowerCase().substring(0,5);//生成一个没有-的uuid,然后取前5位
java.text.DateFormat format1 = new java.text.SimpleDateFormat("MMddhhmmss");
String times = format1.format(new Date());
file = changeFile(entry.getValue());
try {
// 指定要上传到的存储桶
String bucketName = BarrelName;
// 指定要上传到 COS 上对象键
String userkey =username + "/" + uuid+times + "." + entry.getKey();
PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, userkey, file);
PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
ReturnImage returnImage = new ReturnImage();
returnImage.setImgname(entry.getValue().getOriginalFilename());
returnImage.setImgurl(key.getRequestAddress() + "/" + userkey);
ImgUrl.put(returnImage, (int) (entry.getValue().getSize()));
if(setday>0) {
String deleimg = DateUtils.plusDay(setday);
DeleImg.charu(username + "/" + uuid + times + "." + entry.getKey() + "|" + deleimg + "|" + "6");
try {
for (Map.Entry<String, MultipartFile> entry : fileMap.entrySet()) {
String uuid = UUID.randomUUID().toString().replace("-", "").toLowerCase().substring(0,5);//生成一个没有-的uuid,然后取前5位
java.text.DateFormat format1 = new java.text.SimpleDateFormat("MMddhhmmss");
String times = format1.format(new Date());
file = SetFiles.changeFile(entry.getValue());
try {
// 指定要上传到的存储桶
String bucketName = BarrelName;
// 指定要上传到 COS 上对象键
String userkey =username + "/" + uuid+times + "." + entry.getKey();
PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, userkey, file);
PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
ReturnImage returnImage = new ReturnImage();
returnImage.setImgname(userkey);//entry.getValue().getOriginalFilename()
returnImage.setImgurl(key.getRequestAddress() + "/" + userkey);
ImgUrl.put(returnImage, (int) (entry.getValue().getSize()));
if(setday>0) {
String deleimg = DateUtils.plusDay(setday);
DeleImg.charu(username + "/" + uuid + times + "." + entry.getKey() + "|" + deleimg + "|" + "6");
}
} catch (CosServiceException serverException) {
serverException.printStackTrace();
} catch (CosClientException clientException) {
clientException.printStackTrace();
}
} catch (CosServiceException serverException) {
serverException.printStackTrace();
} catch (CosClientException clientException) {
clientException.printStackTrace();
}
}catch(Exception e){
e.printStackTrace();
ImgUrl.put(null, 500);
}
return ImgUrl;
}else{
Map<ReturnImage, Integer> ImgUrl = new HashMap<>();
ObjectMetadata meta = new ObjectMetadata();
meta.setHeader("Content-Disposition", "inline");
for (Map.Entry<String, String> entry : fileMap2.entrySet()) {
String uuid = UUID.randomUUID().toString().replace("-", "").toLowerCase().substring(0,5);//生成一个没有-的uuid,然后取前5位
java.text.DateFormat format1 = new java.text.SimpleDateFormat("MMddhhmmss");
String times = format1.format(new Date());
String imgurl = entry.getValue();
File file = new File(imgurl);
FileInputStream fileInputStream = new FileInputStream(file);
try {
String userkey =username + "/" + uuid+times + "." + entry.getKey();
PutObjectRequest putObjectRequest = new PutObjectRequest(BarrelName, userkey, file);
PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
ReturnImage returnImage = new ReturnImage();
returnImage.setImgurl(key.getRequestAddress() + "/" + userkey);
ImgUrl.put(returnImage, ImgUrlUtil.getFileSize2(new File(imgurl)));
if(setday>0) {
String deleimg = DateUtils.plusDay(setday);
DeleImg.charu(username + "/" + uuid + times + "." + entry.getKey() + "|" + deleimg + "|" + "6");
try {
for (Map.Entry<String, String> entry : fileMap2.entrySet()) {
String uuid = UUID.randomUUID().toString().replace("-", "").toLowerCase().substring(0,5);//生成一个没有-的uuid,然后取前5位
java.text.DateFormat format1 = new java.text.SimpleDateFormat("MMddhhmmss");
String times = format1.format(new Date());
String imgurl = entry.getValue();
File file = new File(imgurl);
FileInputStream fileInputStream = new FileInputStream(file);
try {
String userkey =username + "/" + uuid+times + "." + entry.getKey();
PutObjectRequest putObjectRequest = new PutObjectRequest(BarrelName, userkey, file);
PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
ReturnImage returnImage = new ReturnImage();
returnImage.setImgurl(key.getRequestAddress() + "/" + userkey);
ImgUrl.put(returnImage, ImgUrlUtil.getFileSize2(new File(imgurl)));
if(setday>0) {
String deleimg = DateUtils.plusDay(setday);
DeleImg.charu(username + "/" + uuid + times + "." + entry.getKey() + "|" + deleimg + "|" + "6");
}
boolean bb= new File(imgurl).getAbsoluteFile().delete();
Print.Normal("删除情况"+bb);
} catch (Exception e) {
System.err.println("上传报错:" + e.getMessage());
}
if(fileInputStream!=null){
fileInputStream.close();
Print.Normal("流已经关闭");
}
boolean bb= new File(imgurl).getAbsoluteFile().delete();
Print.Normal("删除情况"+bb);
} catch (Exception e) {
System.err.println("上传报错:" + e.getMessage());
}
if(fileInputStream!=null){
fileInputStream.close();
Print.Normal("流已经关闭");
}
}catch(Exception e){
ImgUrl.put(null, 500);
}
cosClient.shutdown();
return ImgUrl;
}
}
// 转换文件方法
private File changeFile(MultipartFile multipartFile) throws Exception {
// 获取文件名
String fileName = multipartFile.getOriginalFilename();
// 获取文件后缀
String prefix = fileName.substring(fileName.lastIndexOf("."));
// todo 修改临时文件文件名
File file = File.createTempFile(fileName, prefix);
multipartFile.transferTo(file);
return file;
}
//初始化网易NOS对象存储
public static Integer Initialize(Keys k) {
int ret = -1;
if(k.getEndpoint()!=null && k.getAccessSecret()!=null && k.getEndpoint()!=null
&& k.getBucketname()!=null && k.getRequestAddress()!=null ) {
if(!k.getEndpoint().equals("") && !k.getAccessSecret().equals("") && !k.getEndpoint().equals("")
&& !k.getBucketname().equals("") && !k.getRequestAddress().equals("") ) {
if (!k.getEndpoint().equals("") && !k.getAccessSecret().equals("") && !k.getEndpoint().equals("")
&& !k.getBucketname().equals("") && !k.getRequestAddress().equals("")) {
String secretId = k.getAccessKey();
String secretKey = k.getAccessSecret();
COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
@@ -131,8 +123,20 @@ public class COSImageupload {
ClientConfig clientConfig = new ClientConfig(region);
cosClient = new COSClient(cred, clientConfig);
BarrelName = k.getBucketname();
key = k;
ret = 1;
ListObjectsRequest listObjectsRequest = new ListObjectsRequest();
listObjectsRequest.setBucketName(k.getBucketname());
listObjectsRequest.setDelimiter("/");
listObjectsRequest.setMaxKeys(1);
ObjectListing objectListing = null;
try {
objectListing = cosClient.listObjects(listObjectsRequest);
key = k;
ret = 1;
} catch (Exception e) {
System.out.println("COS - Waiting for configuration。");
ret = -1;
}
}
}
return ret;
@@ -148,7 +152,7 @@ public class COSImageupload {
String uuid = UUID.randomUUID().toString().replace("-", "").toLowerCase().substring(0,5);//生成一个没有-的uuid,然后取前5位
java.text.DateFormat format1 = new java.text.SimpleDateFormat("MMddhhmmss");
String times = format1.format(new Date());
file = changeFile(entry.getValue());
file = SetFiles.changeFile_c(entry.getValue());
try {
ReturnImage returnImage = new ReturnImage();
if(entry.getValue().getSize()/1024<=uploadConfig.getFilesizeuser()*1024){
@@ -1,23 +0,0 @@
package cn.hellohao.service.impl;
import cn.hellohao.dao.DomainMapper;
import cn.hellohao.pojo.Domain;
import cn.hellohao.service.DomainService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* @author Hellohao
* @version 1.0
* @date 2019/8/21 9:51
*/
@Service
public class DomainServiceImpl implements DomainService {
@Autowired
private DomainMapper domainMapper;
@Override
public Integer getDomain(String domain) {
return domainMapper.getDomain(domain);
}
}
@@ -21,7 +21,7 @@ public class FTPImageupload {
static Keys key;
public Map<ReturnImage, Integer> ImageuploadFTP(Map<String, MultipartFile> fileMap, String username,
Map<String, String> fileMap2,Integer setday) throws Exception {
Map<String, String> fileMap2,Integer setday) {
String[] host = key.getEndpoint().split("\\:");
String h = host[0];
Integer p = Integer.parseInt(host[1]);
@@ -32,68 +32,66 @@ public class FTPImageupload {
File file = null;
Map<ReturnImage, Integer> ImgUrl = new HashMap<>();
ftps.mkDir(File.separator+username);
for (Map.Entry<String, MultipartFile> entry : fileMap.entrySet()) {
String uuid = UUID.randomUUID().toString().replace("-", "").toLowerCase().substring(0,5);//生成一个没有-的uuid,然后取前5位
java.text.DateFormat format1 = new java.text.SimpleDateFormat("MMddhhmmss");
String times = format1.format(new Date());
file = changeFile(entry.getValue());
String userkey =username + File.separator+ uuid+times + "." + entry.getKey();
if (flag) {
ftps.upload(file, File.separator+userkey, "");
ReturnImage returnImage = new ReturnImage();
returnImage.setImgname(entry.getValue().getOriginalFilename());
returnImage.setImgurl(key.getRequestAddress() + File.separator+ userkey);
ImgUrl.put(returnImage, (int) (entry.getValue().getSize()));
if(setday>0) {
String deleimg = DateUtils.plusDay(setday);
DeleImg.charu(username + "/" + uuid + times + "." + entry.getKey() + "|" + deleimg + "|" + "7");
try {
for (Map.Entry<String, MultipartFile> entry : fileMap.entrySet()) {
String uuid = UUID.randomUUID().toString().replace("-", "").toLowerCase().substring(0,5);//生成一个没有-的uuid,然后取前5位
java.text.DateFormat format1 = new java.text.SimpleDateFormat("MMddhhmmss");
String times = format1.format(new Date());
file = SetFiles.changeFile(entry.getValue());
String userkey =username + "/"+ uuid+times + "." + entry.getKey();
if (flag) {
ftps.upload(file, File.separator+userkey, "");
ReturnImage returnImage = new ReturnImage();
returnImage.setImgname(userkey);//entry.getValue().getOriginalFilename()
returnImage.setImgurl(key.getRequestAddress() + "/"+ userkey);
ImgUrl.put(returnImage, (int) (entry.getValue().getSize()));
if(setday>0) {
String deleimg = DateUtils.plusDay(setday);
DeleImg.charu(username + "/" + uuid + times + "." + entry.getKey() + "|" + deleimg + "|" + "7");
}
ftps.close();
}
ftps.close();
}
Print.Normal("要上传的文件路径:"+File.separator+userkey);
Print.Normal("要上传的文件路径:"+File.separator+userkey);
}
}catch (Exception e){
e.printStackTrace();
ImgUrl.put(null, 500);
}
return ImgUrl;
}else{
Map<ReturnImage, Integer> ImgUrl = new HashMap<>();
for (Map.Entry<String, String> entry : fileMap2.entrySet()) {
String uuid = UUID.randomUUID().toString().replace("-", "").toLowerCase().substring(0,5);//生成一个没有-的uuid,然后取前5位
java.text.DateFormat format1 = new java.text.SimpleDateFormat("MMddhhmmss");
String times = format1.format(new Date());
String imgurl = entry.getValue();
File file = new File(imgurl);
String userkey =username + File.separator+ uuid+times + "." + entry.getKey();
ftps.mkDir(File.separator+username);
if (flag) {
ftps.upload(file, File.separator+userkey, "");
ReturnImage returnImage = new ReturnImage();
returnImage.setImgurl(key.getRequestAddress() + File.separator+ userkey);
ImgUrl.put(returnImage, ImgUrlUtil.getFileSize2(new File(imgurl)));
if(setday>0) {
String deleimg = DateUtils.plusDay(setday);
DeleImg.charu(username + "/" + uuid + times + "." + entry.getKey() + "|" + deleimg + "|" + "7");
try {
for (Map.Entry<String, String> entry : fileMap2.entrySet()) {
String uuid = UUID.randomUUID().toString().replace("-", "").toLowerCase().substring(0,5);//生成一个没有-的uuid,然后取前5位
java.text.DateFormat format1 = new java.text.SimpleDateFormat("MMddhhmmss");
String times = format1.format(new Date());
String imgurl = entry.getValue();
File file = new File(imgurl);
String userkey =username + File.separator+ uuid+times + "." + entry.getKey();
ftps.mkDir(File.separator+username);
if (flag) {
ftps.upload(file, File.separator+userkey, "");
ReturnImage returnImage = new ReturnImage();
returnImage.setImgurl(key.getRequestAddress() + File.separator+ userkey);
ImgUrl.put(returnImage, ImgUrlUtil.getFileSize2(new File(imgurl)));
if(setday>0) {
String deleimg = DateUtils.plusDay(setday);
DeleImg.charu(username + "/" + uuid + times + "." + entry.getKey() + "|" + deleimg + "|" + "7");
}
ftps.close();
}
ftps.close();
boolean bb= new File(imgurl).getAbsoluteFile().delete();
Print.Normal("删除情况"+bb);
}
boolean bb= new File(imgurl).getAbsoluteFile().delete();
Print.Normal("删除情况"+bb);
}catch (Exception e){
e.printStackTrace();
ImgUrl.put(null, 500);
}
return ImgUrl;
}
}
// 转换文件方法
private File changeFile(MultipartFile multipartFile) throws Exception {
// 获取文件名
String fileName = multipartFile.getOriginalFilename();
// 获取文件后缀
String prefix = fileName.substring(fileName.lastIndexOf("."));
// todo 修改临时文件文件名
File file = File.createTempFile(fileName, prefix);
multipartFile.transferTo(file);
return file;
}
//初始化FTP对象存储
public static Integer Initialize(Keys k) {
int ret = -1;
@@ -101,37 +99,39 @@ public class FTPImageupload {
if(!k.getEndpoint().equals("") && !k.getAccessSecret().equals("") && !k.getEndpoint().equals("") && !k.getRequestAddress().equals("") ) {
FTPClient ftp = new FTPClient();
int flag = k.getEndpoint().indexOf(":");
if(flag>0){
String[] host = k.getEndpoint().split("\\:");
String h = host[0];
Integer p = Integer.parseInt(host[1]);
try {
if(!ftp.isConnected()){
ftp.connect(h,p);
}
ftp.login(k.getAccessKey(), k.getAccessSecret());
} catch (IOException e) {
e.printStackTrace();
}
//获取服务器返回的状态码
int reply = ftp.getReplyCode();
/*
* 判断是否连接成功
* 所有以2开头的代码是正完成响应。
* FTP服务器将在最终发送一个肯定的完成响应成功完成命令。
*/
if (!FTPReply.isPositiveCompletion(reply)) {
if(flag>0){
String[] host = k.getEndpoint().split("\\:");
String h = host[0];
Integer p = Integer.parseInt(host[1]);
try {
ftp.disconnect();
}catch (IOException e){
e.printStackTrace();
if(!ftp.isConnected()){
ftp.connect(h,p);
}
ftp.login(k.getAccessKey(), k.getAccessSecret());
//获取服务器返回的状态码
int reply = ftp.getReplyCode();
/*
* 判断是否连接成功
* 所有以2开头的代码是正完成响应。
* FTP服务器将在最终发送一个肯定的完成响应成功完成命令。
*/
if (!FTPReply.isPositiveCompletion(reply)) {
System.out.println("FTP - Waiting for configuration");
ftp.disconnect();
return -1;
}
ftpClient1 = ftp;
key = k;
ret = 1;
// if(ftp.printWorkingDirectory()==null){
// Print.warning("FTP初始化失败,配置项错误");
// return -1;
// }
} catch (IOException e) {
System.out.println("FTP - Waiting for configuration");
return -1;
}
ret = -1;
}
ftpClient1 = ftp;
key = k;
ret = 1;
}
}
}
}
return ret;
@@ -152,7 +152,7 @@ public class FTPImageupload {
String uuid = UUID.randomUUID().toString().replace("-", "").toLowerCase().substring(0,5);//生成一个没有-的uuid,然后取前5位
java.text.DateFormat format1 = new java.text.SimpleDateFormat("MMddhhmmss");
String times = format1.format(new Date());
file = changeFile(entry.getValue());
file = SetFiles.changeFile_c(entry.getValue());
String userkey =username + File.separator+ uuid+times + "." + entry.getKey();
ftps.mkDir(File.separator+username);
if (flag) {
@@ -0,0 +1,45 @@
package cn.hellohao.service.impl;
import cn.hellohao.dao.ImgAndAlbumMapper;
import cn.hellohao.pojo.Images;
import cn.hellohao.pojo.ImgAndAlbum;
import cn.hellohao.service.ImgAndAlbumService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* @author Tiansh
* @version 1.0
* @date 2019/12/19 15:40
*/
@Service
public class ImgAndAlbumServiceImpl implements ImgAndAlbumService {
@Autowired
ImgAndAlbumMapper imgAndAlbumMapper;
@Override
public Integer addImgAndAlbum(ImgAndAlbum imgAndAlbum) {
return imgAndAlbumMapper.addImgAndAlbum(imgAndAlbum);
}
@Override
public List<ImgAndAlbum> getAlbumForImgname(String imgname) {
return imgAndAlbumMapper.getAlbumForImgname(imgname);
}
@Override
public Integer deleteImgAndAlbum(String imgname) {
return imgAndAlbumMapper.deleteImgAndAlbum(imgname);
}
@Override
public Integer deleteImgAndAlbumForKey(String albumkey) {
return imgAndAlbumMapper.deleteImgAndAlbumForKey(albumkey);
}
@Override
public List<Images> selectImgForAlbumkey(String albumkey) {
return imgAndAlbumMapper.selectImgForAlbumkey(albumkey);
}
}
@@ -107,6 +107,17 @@ public class ImgServiceImpl implements ImgService {
e.printStackTrace();
}
}
public void delectUFile(Keys key, String fileName) {
UpYun upyun = new UpYun(key.getBucketname(), key.getAccessKey(), key.getAccessSecret());
try {
boolean result = upyun.deleteFile(fileName, null);
} catch (IOException e) {
e.printStackTrace();
} catch (UpException e) {
e.printStackTrace();
}
}
public void delectKODO(Keys key, String fileName) {
Configuration cfg;
if(key.getEndpoint().equals("1")){cfg = new Configuration(Zone.zone0());}
@@ -169,8 +180,8 @@ public class ImgServiceImpl implements ImgService {
}
@Override
public Integer setabnormal(String imgname,String abnormal) {
return imgMapper.setabnormal(imgname,abnormal);
public Integer setImg(Images images) {
return imgMapper.setImg(images);
}
@Override
@@ -192,4 +203,14 @@ public class ImgServiceImpl implements ImgService {
public Integer getusermemory(Integer userid) {
return imgMapper.getusermemory(userid);
}
@Override
public Integer md5Count(String md5key) {
return imgMapper.md5Count(md5key);
}
@Override
public Images selectImgUrlByMD5(String md5key) {
return imgMapper.selectImgUrlByMD5(md5key);
}
}
@@ -8,6 +8,7 @@ import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import java.lang.management.ManagementFactory;
import java.util.List;
/**
@@ -17,13 +18,18 @@ import java.util.List;
*/
@Component
@Order(2) //通过order值的大小来决定启动的顺序
@Order(2)
public class InitializationStorage implements CommandLineRunner {
@Autowired
private KeysMapper keysMapper;
@Override
public void run(String... args) throws Exception {
String name = ManagementFactory.getRuntimeMXBean().getName();
//System.out.println(name);
// get pid
String pid = name.split("@")[0];
//System.out.println("Pid is:" + pid);
intiStorage();
sout();
}
@@ -33,7 +39,7 @@ public class InitializationStorage implements CommandLineRunner {
if(key.getStorageType()!=0 && key.getStorageType()!=null){
int ret =0;
if(key.getStorageType()==1){
ret =NOSImageupload.Initialize(key);//实例化网易
ret =NOSImageupload.Initialize(key);
}else if (key.getStorageType()==2){
ret =OSSImageupload.Initialize(key);
}else if(key.getStorageType()==3){
@@ -44,15 +50,17 @@ public class InitializationStorage implements CommandLineRunner {
ret = COSImageupload.Initialize(key);
}else if(key.getStorageType()==7){
ret = FTPImageupload.Initialize(key);
}else if(key.getStorageType()==8){
ret = UFileImageupload.Initialize(key);
}
}
}
Print.Normal("初始化完成");
//Print.Normal("66666666");
}
public void sout(){
Print.Normal("______________________________________________");
Print.Normal(" Hellohao-Pro ");
Print.Normal(" Hellohao-Open source ");
Print.Normal(" Successful startup of the program ");
Print.Normal(" is OK! Open http://your ip:port ");
Print.Normal("______________________________________________");
@@ -3,9 +3,7 @@ package cn.hellohao.service.impl;
import cn.hellohao.pojo.Keys;
import cn.hellohao.pojo.ReturnImage;
import cn.hellohao.pojo.UploadConfig;
import cn.hellohao.utils.DateUtils;
import cn.hellohao.utils.DeleImg;
import cn.hellohao.utils.ImgUrlUtil;
import cn.hellohao.utils.*;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.ObjectMetadata;
import com.google.gson.Gson;
@@ -16,6 +14,7 @@ import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.storage.model.FileInfo;
import com.qiniu.util.Auth;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
@@ -33,80 +32,89 @@ public class KODOImageupload {
static Keys key;
public Map<ReturnImage, Integer> ImageuploadKODO(Map<String, MultipartFile> fileMap, String username,
Map<String, String> fileMap2,Integer setday) throws Exception {
Map<String, String> fileMap2,Integer setday){
if(fileMap2==null){
File file = null;
Map<ReturnImage, Integer> ImgUrl = new HashMap<>();
for (Map.Entry<String, MultipartFile> entry : fileMap.entrySet()) {
String uuid = UUID.randomUUID().toString().replace("-", "").toLowerCase().substring(0,5);//生成一个没有-的uuid,然后取前5位
java.text.DateFormat format1 = new java.text.SimpleDateFormat("MMddhhmmss");
String times = format1.format(new Date());
file = changeFile(entry.getValue());
try {
Response response = uploadManager.put(file,username + "/" + uuid+times + "." + entry.getKey(),upToken);
DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
ReturnImage returnImage = new ReturnImage();
returnImage.setImgname(entry.getValue().getOriginalFilename());
returnImage.setImgurl(key.getRequestAddress() + "/" + username + "/" + uuid+times + "." + entry.getKey());
ImgUrl.put(returnImage, (int) (entry.getValue().getSize()));
if(setday>0) {
String deleimg = DateUtils.plusDay(setday);
DeleImg.charu(username + "/" + uuid + times + "." + entry.getKey() + "|" + deleimg + "|" + "4");
}
} catch (QiniuException ex) {
Response r = ex.response;
System.err.println(r.toString());
try {
for (Map.Entry<String, MultipartFile> entry : fileMap.entrySet()) {
String uuid = UUID.randomUUID().toString().replace("-", "").toLowerCase().substring(0,5);//生成一个没有-的uuid,然后取前5位
java.text.DateFormat format1 = new java.text.SimpleDateFormat("MMddhhmmss");
String times = format1.format(new Date());
file = SetFiles.changeFile(entry.getValue());
try {
System.err.println(r.bodyString());
} catch (QiniuException ex2) {
Response response = uploadManager.put(file,username + "/" + uuid+times + "." + entry.getKey(),upToken);
DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
ReturnImage returnImage = new ReturnImage();
returnImage.setImgname(username + "/" + uuid+times + "." + entry.getKey());//entry.getValue().getOriginalFilename()
returnImage.setImgurl(key.getRequestAddress() + "/" + username + "/" + uuid+times + "." + entry.getKey());
ImgUrl.put(returnImage, (int) (entry.getValue().getSize()));
if(setday>0) {
String deleimg = DateUtils.plusDay(setday);
DeleImg.charu(username + "/" + uuid + times + "." + entry.getKey() + "|" + deleimg + "|" + "4");
}
} catch (QiniuException ex) {
Response r = ex.response;
System.err.println(r.toString());
try {
System.err.println(r.bodyString());
} catch (QiniuException ex2) {
}
}
}
}catch (Exception e){
e.printStackTrace();
ImgUrl.put(null, 500);
}
return ImgUrl;
}else{
Map<ReturnImage, Integer> ImgUrl = new HashMap<>();
for (Map.Entry<String, String> entry : fileMap2.entrySet()) {
String uuid = UUID.randomUUID().toString().replace("-", "").toLowerCase().substring(0,5);//生成一个没有-的uuid,然后取前5位
java.text.DateFormat format1 = new java.text.SimpleDateFormat("MMddhhmmss");
String times = format1.format(new Date());
String imgurl = entry.getValue();
System.out.println("待上传的图片:"+username + "/" + uuid+times + "." + entry.getKey());
try {
Response response = uploadManager.put(new File(imgurl),username + "/" + uuid+times + "." + entry.getKey(),upToken);
DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
ReturnImage returnImage = new ReturnImage();
returnImage.setImgurl(key.getRequestAddress() + "/" + username + "/" + uuid+times + "." + entry.getKey());
ImgUrl.put(returnImage, ImgUrlUtil.getFileSize2(new File(imgurl)));
if(setday>0) {
String deleimg = DateUtils.plusDay(setday);
DeleImg.charu(username + "/" + uuid + times + "." + entry.getKey() + "|" + deleimg + "|" + "4");
}
new File(imgurl).delete();
} catch (QiniuException ex) {
Response r = ex.response;
System.err.println(r.toString());
try {
for (Map.Entry<String, String> entry : fileMap2.entrySet()) {
String uuid = UUID.randomUUID().toString().replace("-", "").toLowerCase().substring(0,5);//生成一个没有-的uuid,然后取前5位
java.text.DateFormat format1 = new java.text.SimpleDateFormat("MMddhhmmss");
String times = format1.format(new Date());
String imgurl = entry.getValue();
System.out.println("待上传的图片:"+username + "/" + uuid+times + "." + entry.getKey());
try {
System.err.println(r.bodyString());
} catch (QiniuException ex2) {
Response response = uploadManager.put(new File(imgurl),username + "/" + uuid+times + "." + entry.getKey(),upToken);
DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
ReturnImage returnImage = new ReturnImage();
returnImage.setImgurl(key.getRequestAddress() + "/" + username + "/" + uuid+times + "." + entry.getKey());
ImgUrl.put(returnImage, ImgUrlUtil.getFileSize2(new File(imgurl)));
if(setday>0) {
String deleimg = DateUtils.plusDay(setday);
DeleImg.charu(username + "/" + uuid + times + "." + entry.getKey() + "|" + deleimg + "|" + "4");
}
new File(imgurl).delete();
} catch (QiniuException ex) {
Response r = ex.response;
System.err.println(r.toString());
try {
System.err.println(r.bodyString());
} catch (QiniuException ex2) {
}
}
}
}catch (Exception e){
e.printStackTrace();
ImgUrl.put(null, 500);
}
return ImgUrl;
}
}
// 转换文件方法
private File changeFile(MultipartFile multipartFile) throws Exception {
// 获取文件名
String fileName = multipartFile.getOriginalFilename();
// 获取文件后缀
String prefix = fileName.substring(fileName.lastIndexOf("."));
// todo 修改临时文件文件名
File file = File.createTempFile(fileName, prefix);
multipartFile.transferTo(file);
return file;
}
// private File changeFile(MultipartFile multipartFile) throws Exception {
// // 获取文件名
// String fileName = multipartFile.getOriginalFilename();
// // 获取文件后缀
// String prefix = fileName.substring(fileName.lastIndexOf("."));
// // todo 修改临时文件文件名
// File file = File.createTempFile(fileName, prefix);
// multipartFile.transferTo(file);
// return file;
// }
//初始化
public static Integer Initialize(Keys k) {
@@ -130,8 +138,20 @@ public class KODOImageupload {
uploadManager = new UploadManager(cfg);
Auth auth = Auth.create(k.getAccessKey(), k.getAccessSecret());
upToken = auth.uploadToken(k.getBucketname());
key = k;
ret = 1;
BucketManager bucketManager = new BucketManager(auth, cfg);
BucketManager.FileListIterator fileListIterator = null;
try {
fileListIterator = bucketManager.createFileListIterator(k.getBucketname(), "", 1, "/");
FileInfo[] items = fileListIterator.next();
System.out.println(items!=null);
if(items!=null){
key = k;
ret = 1;
}
}catch (Exception e){
System.out.println("KODO - Waiting for configuration");
ret = -1;
}
}
}
return ret;
@@ -147,7 +167,7 @@ public class KODOImageupload {
String uuid = UUID.randomUUID().toString().replace("-", "").toLowerCase().substring(0,5);//生成一个没有-的uuid,然后取前5位
java.text.DateFormat format1 = new java.text.SimpleDateFormat("MMddhhmmss");
String times = format1.format(new Date());
file = changeFile(entry.getValue());
file = SetFiles.changeFile_c(entry.getValue());
System.out.println("待上传的图片:"+username + "/" + uuid+times + "." + entry.getKey());
try {
ReturnImage returnImage = new ReturnImage();
@@ -29,7 +29,7 @@ public class KeysServiceImpl implements KeysService {
@Override
public List<Keys> getKeys() {
return null;
return keysMapper.getKeys();
}
}
@@ -2,19 +2,14 @@ package cn.hellohao.service.impl;
import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.*;
import cn.hellohao.exception.StorageSourceInitException;
import cn.hellohao.pojo.ReturnImage;
import cn.hellohao.pojo.UploadConfig;
import cn.hellohao.utils.DateUtils;
import cn.hellohao.utils.DeleImg;
import cn.hellohao.utils.ImgUrlUtil;
import cn.hellohao.utils.Print;
import cn.hellohao.utils.*;
import com.netease.cloud.services.nos.model.NOSObjectSummary;
import com.netease.cloud.services.nos.model.ObjectListing;
import com.netease.cloud.services.nos.model.ObjectMetadata;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
@@ -34,68 +29,79 @@ public class NOSImageupload {
static Keys key;
public Map<ReturnImage, Integer> Imageupload(Map<String, MultipartFile> fileMap, String username,
Map<String, String> fileMap2,Integer setday) throws Exception {
Map<String, String> fileMap2,Integer setday){
if(fileMap2==null){
File file = null;
Map<ReturnImage, Integer> ImgUrl = new HashMap<>();
for (Map.Entry<String, MultipartFile> entry : fileMap.entrySet()) {
String uuid = UUID.randomUUID().toString().replace("-", "").toLowerCase().substring(0,5);//生成一个没有-的uuid,然后取前5位
java.text.DateFormat format1 = new java.text.SimpleDateFormat("MMddhhmmss");
String times = format1.format(new Date());
file = changeFile(entry.getValue());
nosClient.putObject(BarrelName, username + "/" + uuid+times + "." + entry.getKey(), file);
ReturnImage returnImage = new ReturnImage();
returnImage.setImgname(entry.getValue().getOriginalFilename());
returnImage.setImgurl(key.getRequestAddress() + "/" + username + "/" + uuid+times + "." + entry.getKey());
ImgUrl.put(returnImage, (int) (entry.getValue().getSize()));
if(setday>0){
String deleimg = DateUtils.plusDay(setday);
DeleImg.charu(username + "/" + uuid+times + "." + entry.getKey()+"-"+deleimg+"-"+"1");
try {
for (Map.Entry<String, MultipartFile> entry : fileMap.entrySet()) {
String uuid = UUID.randomUUID().toString().replace("-", "").toLowerCase().substring(0,5);//生成一个没有-的uuid,然后取前5位
java.text.DateFormat format1 = new java.text.SimpleDateFormat("MMddhhmmss");
String times = format1.format(new Date());
file = SetFiles.changeFile(entry.getValue());
nosClient.putObject(BarrelName, username + "/" + uuid+times + "." + entry.getKey(), file);
ReturnImage returnImage = new ReturnImage();
returnImage.setImgname(username + "/" + uuid+times + "." + entry.getKey());//entry.getValue().getOriginalFilename()
returnImage.setImgurl(key.getRequestAddress() + "/" + username + "/" + uuid+times + "." + entry.getKey());
ImgUrl.put(returnImage, (int) (entry.getValue().getSize()));
if(setday>0){
String deleimg = DateUtils.plusDay(setday);
DeleImg.charu(username + "/" + uuid+times + "." + entry.getKey()+"-"+deleimg+"-"+"1");
}
}
}catch (Exception e){
e.printStackTrace();
ImgUrl.put(null, 500);
}
return ImgUrl;
}else{
Map<ReturnImage, Integer> ImgUrl = new HashMap<>();
ObjectMetadata meta = new ObjectMetadata();
meta.setHeader("Content-Disposition", "inline");
for (Map.Entry<String, String> entry : fileMap2.entrySet()) {
String uuid = UUID.randomUUID().toString().replace("-", "").toLowerCase().substring(0,5);//生成一个没有-的uuid,然后取前5位
java.text.DateFormat format1 = new java.text.SimpleDateFormat("MMddhhmmss");
String times = format1.format(new Date());
String imgurl = entry.getValue();
String head = "";
if(entry.getKey().equals("jpg")||entry.getKey().equals("jpeg")){
head = "image/jpeg";
}else if(entry.getKey().equals("png")){
head = "image/png";
}else if(entry.getKey().equals("bmp")){
head = "image/bmp";
}else if(entry.getKey().equals("gif")){
head = "image/gif";
}else{
System.err.println("未知格式文件,无法定义header头。");
}
meta.setHeader("Content-Type", head);//image/jpeg
File file = new File(imgurl);
FileInputStream fileInputStream = new FileInputStream(file);
try {
nosClient.putObject(BarrelName, username + "/" + uuid+times + "." + entry.getKey(), fileInputStream,meta);
ReturnImage returnImage = new ReturnImage();
returnImage.setImgurl(key.getRequestAddress() + "/" + username + "/" + uuid+times + "." + entry.getKey());
ImgUrl.put(returnImage, ImgUrlUtil.getFileSize2(new File(imgurl)));
if(setday>0) {
String deleimg = DateUtils.plusDay(setday);
DeleImg.charu(username + "/" + uuid + times + "." + entry.getKey() + "-" + deleimg + "-" + "1");
try {
for (Map.Entry<String, String> entry : fileMap2.entrySet()) {
String uuid = UUID.randomUUID().toString().replace("-", "").toLowerCase().substring(0,5);//生成一个没有-的uuid,然后取前5位
java.text.DateFormat format1 = new java.text.SimpleDateFormat("MMddhhmmss");
String times = format1.format(new Date());
String imgurl = entry.getValue();
String head = "";
if(entry.getKey().equals("jpg")||entry.getKey().equals("jpeg")){
head = "image/jpeg";
}else if(entry.getKey().equals("png")){
head = "image/png";
}else if(entry.getKey().equals("bmp")){
head = "image/bmp";
}else if(entry.getKey().equals("gif")){
head = "image/gif";
}else{
//System.err.println("未知格式文件,无法定义header头。");
head = "image/"+entry.getKey();
}
meta.setHeader("Content-Type", head);//image/jpeg
File file = new File(imgurl);
FileInputStream fileInputStream = new FileInputStream(file);
try {
nosClient.putObject(BarrelName, username + "/" + uuid+times + "." + entry.getKey(), fileInputStream,meta);
ReturnImage returnImage = new ReturnImage();
returnImage.setImgurl(key.getRequestAddress() + "/" + username + "/" + uuid+times + "." + entry.getKey());
ImgUrl.put(returnImage, ImgUrlUtil.getFileSize2(new File(imgurl)));
if(setday>0) {
String deleimg = DateUtils.plusDay(setday);
DeleImg.charu(username + "/" + uuid + times + "." + entry.getKey() + "-" + deleimg + "-" + "1");
}
boolean bb= new File(imgurl).getAbsoluteFile().delete();
Print.Normal("删除情况"+bb);
} catch (Exception e) {
System.err.println("上传报错:" + e.getMessage());
}
if(fileInputStream!=null){
fileInputStream.close();
Print.Normal("流已经关闭");
}
boolean bb= new File(imgurl).getAbsoluteFile().delete();
Print.Normal("删除情况"+bb);
} catch (Exception e) {
System.err.println("上传报错:" + e.getMessage());
}
if(fileInputStream!=null){
fileInputStream.close();
Print.Normal("流已经关闭");
}
}catch (Exception e){
e.printStackTrace();
ImgUrl.put(null, 500);
}
return ImgUrl;
}
@@ -103,17 +109,17 @@ public class NOSImageupload {
}
// 转换文件方法
private File changeFile(MultipartFile multipartFile) throws Exception {
// 获取文件名
String fileName = multipartFile.getOriginalFilename();
// 获取文件后缀
String prefix = fileName.substring(fileName.lastIndexOf("."));
// todo 修改临时文件文件名
File file = File.createTempFile(fileName, prefix);
// MultipartFile to File
multipartFile.transferTo(file);
return file;
}
// private File changeFile(MultipartFile multipartFile) throws Exception {
// // 获取文件名
// String fileName = multipartFile.getOriginalFilename();
// // 获取文件后缀
// String prefix = fileName.substring(fileName.lastIndexOf("."));
// // todo 修改临时文件文件名
// File file = File.createTempFile(fileName, prefix);
// // MultipartFile to File
// multipartFile.transferTo(file);
// return file;
// }
//初始化网易NOS对象存储
@@ -127,28 +133,19 @@ public class NOSImageupload {
Credentials credentials = new BasicCredentials(k.getAccessKey(), k.getAccessSecret());
nosClient = new NosClient(credentials);
nosClient.setEndpoint(k.getEndpoint());
// 列举桶
ArrayList bucketList = new ArrayList();
//加入传入的key值不正确,这里会报异常,页面500,如何捕捉异常处理。
BarrelName = k.getBucketname();
// for (Bucket bucket : nosClient.listBuckets()) {
// bucketList.add(bucket.getName());
// }
// for (Object object : bucketList) {
// if (object.toString().equals(k.getBucketname())) {
// BarrelName = object.toString();
// }
// }
key = k;
ret = 1;
}else{
ret = -1;
ObjectListing objectListing = null;
try {
objectListing = nosClient.listObjects(k.getBucketname());
key = k;
ret = 1;
}catch (Exception e){
System.out.println("NOS - Waiting for configuration");
ret = -1;
}
}
}else{
ret = -1;
//throw new StorageSourceInitException("当前数据源配置不完整,请管理员前往后台配置。");
}
//throw new StorageSourceInitException("当前数据源配置不完整,请管理员前往后台配置。");
return ret;
}
@@ -162,7 +159,7 @@ public class NOSImageupload {
String uuid = UUID.randomUUID().toString().replace("-", "").toLowerCase().substring(0,5);//生成一个没有-的uuid,然后取前5位
java.text.DateFormat format1 = new java.text.SimpleDateFormat("MMddhhmmss");
String times = format1.format(new Date());
file = changeFile(entry.getValue());
file = SetFiles.changeFile_c(entry.getValue());
try {
Print.warning(entry.getValue().getSize());
ReturnImage returnImage = new ReturnImage();
@@ -5,15 +5,14 @@ import cn.hellohao.pojo.ReturnImage;
import cn.hellohao.pojo.UploadConfig;
import cn.hellohao.utils.*;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.OSSObjectSummary;
import com.aliyun.oss.model.ObjectListing;
import com.aliyun.oss.model.ObjectMetadata;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.*;
@Service
public class OSSImageupload {
@@ -22,74 +21,86 @@ public class OSSImageupload {
static Keys key;
public Map<ReturnImage, Integer> ImageuploadOSS(Map<String, MultipartFile> fileMap, String username,
Map<String, String> fileMap2,Integer setday) throws Exception {
Map<String, String> fileMap2,Integer setday){
if(fileMap2==null){
File file = null;
Map<ReturnImage, Integer> ImgUrl = new HashMap<>();
ObjectMetadata meta = new ObjectMetadata();
meta.setHeader("Content-Disposition", "inline");
for (Map.Entry<String, MultipartFile> entry : fileMap.entrySet()) {
String uuid = UUID.randomUUID().toString().replace("-", "").toLowerCase().substring(0,5);//生成一个没有-的uuid,然后取前5位
java.text.DateFormat format1 = new java.text.SimpleDateFormat("MMddhhmmss");
String times = format1.format(new Date());
file = SetFiles.changeFile(entry.getValue());
String head = "";
if(entry.getKey().equals("jpg")||entry.getKey().equals("jpeg")){
head = "image/jpeg";
}else if(entry.getKey().equals("png")){
head = "image/png";
}else if(entry.getKey().equals("bmp")){
head = "image/bmp";
}else if(entry.getKey().equals("gif")){
head = "image/gif";
}else{
System.err.println("位置格式文件,无法定义header头。");
}
meta.setHeader("Content-Type", head);//image/jpeg
System.out.println("待上传的图片:"+username + "/" + uuid+times + "." + entry.getKey());
ossClient.putObject(key.getBucketname(), username + "/" + uuid+times + "." + entry.getKey(),file,meta);
ReturnImage returnImage = new ReturnImage();
returnImage.setImgname(entry.getValue().getOriginalFilename());
returnImage.setImgurl(key.getRequestAddress() + "/" + username + "/" + uuid+times + "." + entry.getKey());
ImgUrl.put(returnImage, (int) (entry.getValue().getSize()));
if(setday>0) {
String deleimg = DateUtils.plusDay(setday);
DeleImg.charu(username + "/" + uuid + times + "." + entry.getKey() + "|" + deleimg + "|" + "2");
try {
for (Map.Entry<String, MultipartFile> entry : fileMap.entrySet()) {
String uuid = UUID.randomUUID().toString().replace("-", "").toLowerCase().substring(0,5);//生成一个没有-的uuid,然后取前5位
java.text.DateFormat format1 = new java.text.SimpleDateFormat("MMddhhmmss");
String times = format1.format(new Date());
file = SetFiles.changeFile(entry.getValue());
String head = "";
if(entry.getKey().equals("jpg")||entry.getKey().equals("jpeg")){
head = "image/jpeg";
}else if(entry.getKey().equals("png")){
head = "image/png";
}else if(entry.getKey().equals("bmp")){
head = "image/bmp";
}else if(entry.getKey().equals("gif")){
head = "image/gif";
}else{
//System.err.println("位置格式文件,无法定义header头。");
head = "image/"+entry.getKey();
}
meta.setHeader("Content-Type", head);//image/jpeg
System.out.println("待上传的图片:"+username + "/" + uuid+times + "." + entry.getKey());
ossClient.putObject(key.getBucketname(), username + "/" + uuid+times + "." + entry.getKey(),file,meta);
ReturnImage returnImage = new ReturnImage();
returnImage.setImgname(username + "/" + uuid+times + "." + entry.getKey());//entry.getValue().getOriginalFilename()
returnImage.setImgurl(key.getRequestAddress() + "/" + username + "/" + uuid+times + "." + entry.getKey());
ImgUrl.put(returnImage, (int) (entry.getValue().getSize()));
if(setday>0) {
String deleimg = DateUtils.plusDay(setday);
DeleImg.charu(username + "/" + uuid + times + "." + entry.getKey() + "|" + deleimg + "|" + "2");
}
}
}catch (Exception e){
e.printStackTrace();
ImgUrl.put(null, 500);
}
return ImgUrl;
}else{
Map<ReturnImage, Integer> ImgUrl = new HashMap<>();
ObjectMetadata meta = new ObjectMetadata();
meta.setHeader("Content-Disposition", "inline");
for (Map.Entry<String, String> entry : fileMap2.entrySet()) {
String uuid = UUID.randomUUID().toString().replace("-", "").toLowerCase().substring(0,5);//生成一个没有-的uuid,然后取前5位
java.text.DateFormat format1 = new java.text.SimpleDateFormat("MMddhhmmss");
String times = format1.format(new Date());
String imgurl = entry.getValue();
String head = "";
if(entry.getKey().equals("jpg")||entry.getKey().equals("jpeg")){
head = "image/jpeg";
}else if(entry.getKey().equals("png")){
head = "image/png";
}else if(entry.getKey().equals("bmp")){
head = "image/bmp";
}else if(entry.getKey().equals("gif")){
head = "image/gif";
}else{
System.err.println("位置格式文件,无法定义header头。");
}
meta.setHeader("Content-Type", head);//image/jpeg
System.out.println("待上传的图片:"+username + "/" + uuid+times + "." + entry.getKey());
ossClient.putObject(key.getBucketname(), username + "/" + uuid+times + "." + entry.getKey(),new File(imgurl),meta);
ReturnImage returnImage = new ReturnImage();
returnImage.setImgurl(key.getRequestAddress() + "/" + username + "/" + uuid+times + "." + entry.getKey());
ImgUrl.put(returnImage, ImgUrlUtil.getFileSize2(new File(imgurl)));
new File(imgurl).delete();
if(setday>0) {
String deleimg = DateUtils.plusDay(setday);
DeleImg.charu(username + "/" + uuid + times + "." + entry.getKey() + "|" + deleimg + "|" + "2");
try {
for (Map.Entry<String, String> entry : fileMap2.entrySet()) {
String uuid = UUID.randomUUID().toString().replace("-", "").toLowerCase().substring(0,5);//生成一个没有-的uuid,然后取前5位
java.text.DateFormat format1 = new java.text.SimpleDateFormat("MMddhhmmss");
String times = format1.format(new Date());
String imgurl = entry.getValue();
String head = "";
if(entry.getKey().equals("jpg")||entry.getKey().equals("jpeg")){
head = "image/jpeg";
}else if(entry.getKey().equals("png")){
head = "image/png";
}else if(entry.getKey().equals("bmp")){
head = "image/bmp";
}else if(entry.getKey().equals("gif")){
head = "image/gif";
}else{
//System.err.println("位置格式文件,无法定义header头。");
head = "image/"+entry.getKey();
}
meta.setHeader("Content-Type", head);//image/jpeg
System.out.println("待上传的图片:"+username + "/" + uuid+times + "." + entry.getKey());
ossClient.putObject(key.getBucketname(), username + "/" + uuid+times + "." + entry.getKey(),new File(imgurl),meta);
ReturnImage returnImage = new ReturnImage();
returnImage.setImgurl(key.getRequestAddress() + "/" + username + "/" + uuid+times + "." + entry.getKey());
ImgUrl.put(returnImage, ImgUrlUtil.getFileSize2(new File(imgurl)));
new File(imgurl).delete();
if(setday>0) {
String deleimg = DateUtils.plusDay(setday);
DeleImg.charu(username + "/" + uuid + times + "." + entry.getKey() + "|" + deleimg + "|" + "2");
}
}
}catch (Exception e){
e.printStackTrace();
ImgUrl.put(null, 500);
}
return ImgUrl;
}
@@ -98,19 +109,27 @@ public class OSSImageupload {
//初始化
public static Integer Initialize(Keys k) {
int ret = -1;
ObjectListing objectListing = null;
if(k.getEndpoint()!=null && k.getAccessSecret()!=null && k.getEndpoint()!=null
&& k.getBucketname()!=null && k.getRequestAddress()!=null ) {
if(!k.getEndpoint().equals("") && !k.getAccessSecret().equals("") && !k.getEndpoint().equals("")
&& !k.getBucketname().equals("") && !k.getRequestAddress().equals("") ) {
ossClient = new OSSClient(k.getEndpoint(), k.getAccessKey(), k.getAccessSecret());
key = k;
ret=1;
try {
objectListing = ossClient.listObjects(k.getBucketname());
key = k;
ret=1;
} catch (Exception e) {
System.out.println("OSS - Waiting for configuration");
ret = -1;
}
}
}
return ret;
}
/**
* 客户端接口
* */
@@ -123,7 +142,7 @@ public class OSSImageupload {
String uuid = UUID.randomUUID().toString().replace("-", "").toLowerCase().substring(0,5);//生成一个没有-的uuid,然后取前5位
java.text.DateFormat format1 = new java.text.SimpleDateFormat("MMddhhmmss");
String times = format1.format(new Date());
file = SetFiles.changeFile(entry.getValue());
file = SetFiles.changeFile_c(entry.getValue());
String head = "";
if(entry.getKey().equals("jpg")||entry.getKey().equals("jpeg")){
head = "image/jpeg";
@@ -134,7 +153,8 @@ public class OSSImageupload {
}else if(entry.getKey().equals("gif")){
head = "image/gif";
}else{
System.err.println("位置格式文件,无法定义header头。");
//System.err.println("位置格式文件,无法定义header头。");
head = "image/"+entry.getKey();
}
meta.setHeader("Content-Type", head);//image/jpeg
ReturnImage returnImage = new ReturnImage();
@@ -3,21 +3,17 @@ package cn.hellohao.service.impl;
import cn.hellohao.pojo.Keys;
import cn.hellohao.pojo.ReturnImage;
import cn.hellohao.pojo.UploadConfig;
import cn.hellohao.utils.DateUtils;
import cn.hellohao.utils.DeleImg;
import cn.hellohao.utils.ImgUrlUtil;
import cn.hellohao.utils.Print;
import cn.hellohao.utils.*;
import com.UpYun;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.ObjectMetadata;
import com.upyun.UpException;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.io.IOException;
import java.util.*;
@Service
public class USSImageupload {
@@ -25,74 +21,69 @@ public class USSImageupload {
static Keys key;
public Map<ReturnImage, Integer> ImageuploadUSS(Map<String, MultipartFile> fileMap, String username,
Map<String, String> fileMap2,Integer setday) throws Exception {
Map<String, String> fileMap2,Integer setday) {
if(fileMap2==null){
File file = null;
Map<ReturnImage, Integer> ImgUrl = new HashMap<>();
ObjectMetadata meta = new ObjectMetadata();
meta.setHeader("Content-Disposition", "inline");
for (Map.Entry<String, MultipartFile> entry : fileMap.entrySet()) {
String uuid = UUID.randomUUID().toString().replace("-", "").toLowerCase().substring(0,5);//生成一个没有-的uuid,然后取前5位
java.text.DateFormat format1 = new java.text.SimpleDateFormat("MMddhhmmss");
String times = format1.format(new Date());
file = changeFile(entry.getValue());
upyun.setContentMD5(UpYun.md5(file));
boolean result = upyun.writeFile(username + "/" + uuid+times + "." + entry.getKey(), file, true);
if(result){
ReturnImage returnImage = new ReturnImage();
returnImage.setImgname(entry.getValue().getOriginalFilename());
returnImage.setImgurl(key.getRequestAddress() + "/" + username + "/" + uuid+times + "." + entry.getKey());
ImgUrl.put(returnImage, (int) (entry.getValue().getSize()));
if(setday>0) {
String deleimg = DateUtils.plusDay(setday);
DeleImg.charu(username + "/" + uuid + times + "." + entry.getKey() + "|" + deleimg + "|" + "3");
try {
for (Map.Entry<String, MultipartFile> entry : fileMap.entrySet()) {
String uuid = UUID.randomUUID().toString().replace("-", "").toLowerCase().substring(0,5);//生成一个没有-的uuid,然后取前5位
java.text.DateFormat format1 = new java.text.SimpleDateFormat("MMddhhmmss");
String times = format1.format(new Date());
file = SetFiles.changeFile(entry.getValue());
upyun.setContentMD5(UpYun.md5(file));
boolean result = upyun.writeFile(username + "/" + uuid+times + "." + entry.getKey(), file, true);
if(result){
ReturnImage returnImage = new ReturnImage();
returnImage.setImgname(username + "/" + uuid+times + "." + entry.getKey());//entry.getValue().getOriginalFilename()
returnImage.setImgurl(key.getRequestAddress() + "/" +username + "/" + uuid+times + "." + entry.getKey());//key.getRequestAddress() + "/" +
ImgUrl.put(returnImage, (int) (entry.getValue().getSize()));
if(setday>0) {
String deleimg = DateUtils.plusDay(setday);
DeleImg.charu(username + "/" + uuid + times + "." + entry.getKey() + "|" + deleimg + "|" + "3");
}
}else{
System.err.println("上传失败");
}
}else{
System.err.println("上传失败");
}
}catch (Exception e){
e.printStackTrace();
ImgUrl.put(null, 500);
}
return ImgUrl;
}else{
Map<ReturnImage, Integer> ImgUrl = new HashMap<>();
ObjectMetadata meta = new ObjectMetadata();
meta.setHeader("Content-Disposition", "inline");
for (Map.Entry<String, String> entry : fileMap2.entrySet()) {
String uuid = UUID.randomUUID().toString().replace("-", "").toLowerCase().substring(0,5);//生成一个没有-的uuid,然后取前5位
java.text.DateFormat format1 = new java.text.SimpleDateFormat("MMddhhmmss");
String times = format1.format(new Date());
String imgurl = entry.getValue();
upyun.setContentMD5(UpYun.md5(new File(imgurl)));
boolean result = upyun.writeFile(username + "/" + uuid+times + "." + entry.getKey(), new File(imgurl), true);
if(result){
ReturnImage returnImage = new ReturnImage();
returnImage.setImgurl(key.getRequestAddress() + "/" + username + "/" + uuid+times + "." + entry.getKey());
ImgUrl.put(returnImage, ImgUrlUtil.getFileSize2(new File(imgurl)));
if(setday>0) {
String deleimg = DateUtils.plusDay(setday);
DeleImg.charu(username + "/" + uuid + times + "." + entry.getKey() + "|" + deleimg + "|" + "3");
try {
for (Map.Entry<String, String> entry : fileMap2.entrySet()) {
String uuid = UUID.randomUUID().toString().replace("-", "").toLowerCase().substring(0,5);//生成一个没有-的uuid,然后取前5位
java.text.DateFormat format1 = new java.text.SimpleDateFormat("MMddhhmmss");
String times = format1.format(new Date());
String imgurl = entry.getValue();
upyun.setContentMD5(UpYun.md5(new File(imgurl)));
boolean result = upyun.writeFile(username + "/" + uuid+times + "." + entry.getKey(), new File(imgurl), true);
if(result){
ReturnImage returnImage = new ReturnImage();
returnImage.setImgurl(key.getRequestAddress() + "/" + username + "/" + uuid+times + "." + entry.getKey());
ImgUrl.put(returnImage, ImgUrlUtil.getFileSize2(new File(imgurl)));
if(setday>0) {
String deleimg = DateUtils.plusDay(setday);
DeleImg.charu(username + "/" + uuid + times + "." + entry.getKey() + "|" + deleimg + "|" + "3");
}
}else{
Print.warning("上传失败");
}
}else{
Print.warning("上传失败");
new File(imgurl).delete();
}
new File(imgurl).delete();
}catch (Exception e){
e.printStackTrace();
ImgUrl.put(null, 500);
}
return ImgUrl;
}
}
// 转换文件方法
private File changeFile(MultipartFile multipartFile) throws Exception {
// 获取文件名
String fileName = multipartFile.getOriginalFilename();
// 获取文件后缀
String prefix = fileName.substring(fileName.lastIndexOf("."));
// todo 修改临时文件文件名
File file = File.createTempFile(fileName, prefix);
// MultipartFile to File
multipartFile.transferTo(file);
return file;
}
//初始化
@@ -105,8 +96,15 @@ public class USSImageupload {
// 初始化
// 创建UpYun实例。
upyun = new UpYun(k.getBucketname(), k.getAccessKey(), k.getAccessSecret());
key = k;
ret = 1;
List<UpYun.FolderItem> items = null;
try {
items = upyun.readDir("/",null);
key = k;
ret = 1;
} catch (Exception e) {
System.out.println("USS - Waiting for configuration");
ret = -1;
}
}
}
return ret;
@@ -126,7 +124,7 @@ public class USSImageupload {
String uuid = UUID.randomUUID().toString().replace("-", "").toLowerCase().substring(0,5);//生成一个没有-的uuid,然后取前5位
java.text.DateFormat format1 = new java.text.SimpleDateFormat("MMddhhmmss");
String times = format1.format(new Date());
file = changeFile(entry.getValue());
file = SetFiles.changeFile_c(entry.getValue());
// 上传文件流。
System.out.println("客户端:待上传的图片:"+username + "/" + uuid+times + "." + entry.getKey());
ReturnImage returnImage = new ReturnImage();
@@ -0,0 +1,213 @@
package cn.hellohao.service.impl;
import cn.hellohao.controller.UpdateImgController;
import cn.hellohao.dao.*;
import cn.hellohao.pojo.*;
import cn.hellohao.utils.*;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;
/**
* @author Hellohao
* @version 1.0
* @date 2020/1/9 15:46
*/
@Service
public class UploadServicel {
@Autowired
ConfigMapper configMapper;
@Autowired
UploadConfigMapper uploadConfigMapper;
@Autowired
KeysMapper keysMapper;
@Autowired
ImgMapper imgMapper;
@Autowired
UserMapper userMapper;
public Msg uploadForLoc(HttpSession session, HttpServletRequest request,
MultipartFile multipartFile, Integer setday, String upurlk, String[] iparr) {
Msg msg = new Msg();
JSONArray jsonArray = new JSONArray();
JSONObject jsonObject = new JSONObject();
Config config = configMapper.getSourceype();
UploadConfig uploadConfig = uploadConfigMapper.getUpdateConfig();
String userip = GetIPS.getIpAddr(request);
java.text.DateFormat dateFormat = new java.text.SimpleDateFormat("yyyy/MM/dd");
User u = (User) session.getAttribute("user");
Integer usermemory = 0;
Integer memory = 0;
Integer sourcekey = 0;
Integer maxsize = 0;
String userpath = "tourist";
String md5key = "";
//FileInputStream fis = null;
File file = SetFiles.changeFile_new(multipartFile);
try {
md5key = DigestUtils.md5Hex(new FileInputStream(file));
if(!TypeDict.checkImgType(file)) {
msg.setCode("4000");
return msg;
}
} catch (Exception e) {
e.printStackTrace();
msg.setCode("5000");
return msg;
}
//判断图片是否存在
if(imgMapper.md5Count(md5key)>0){
Print.warning("图片存在啦");
Images images = imgMapper.selectImgUrlByMD5(md5key);
jsonObject.put("imgurls", images.getImgurl());
jsonObject.put("imgnames",file.getName());
jsonArray.add(jsonObject);
msg.setData(jsonArray);
return msg;
}
String prefix = file.getName().substring(file.getName().lastIndexOf(".")+1);
MultipartFile mf =null;
try{
InputStream inputStream = new FileInputStream(file);
mf = new MockMultipartFile(file.getName(), inputStream);
inputStream.close();
}catch (Exception e){
System.out.println("0000000");
}
if (uploadConfig.getBlacklist() != null) {
iparr = uploadConfig.getBlacklist().split(";");
for (String s : iparr) {
if (s.equals(userip)) {
msg.setCode("911");
return msg;
}
}
}
// if (Integer.parseInt(Base64Encryption.decryptBASE64(upurlk)) != yzupdate()) {
if (!upurlk.equals(UpdateImgController.vu)) {
msg.setCode("4003");
return msg;
}
//验证文件是否是图片
if (u == null) {
sourcekey = GetCurrentSource.GetSource(null);
memory = uploadConfig.getVisitormemory();
maxsize = uploadConfig.getFilesizetourists();
usermemory = imgMapper.getusermemory(0);
if (usermemory == null) {
usermemory = 0;
}
} else {
userpath = u.getUsername();
sourcekey = GetCurrentSource.GetSource(u.getId());
memory = userMapper.getUsers(u.getEmail()).getMemory();
maxsize = uploadConfig.getFilesizeuser();
usermemory = imgMapper.getusermemory(u.getId());
if (usermemory == null) {
usermemory = 0;
}
}
if (uploadConfig.getUrltype() == 2) {
userpath = dateFormat.format(new Date());
}
Keys key = keysMapper.selectKeys(sourcekey);
int tmp = (memory == -1 ? -2 : (usermemory / 1024));
if (tmp >= memory) {
msg.setCode("4005");
return msg;
}
long stime = System.currentTimeMillis();
Map<String, MultipartFile> map = new HashMap<>();
if (mf.getSize() > maxsize * 1024 * 1024) {
msg.setCode("4006");
return msg;
}
String fileName = mf.getOriginalFilename();
if (!mf.isEmpty()) {
map.put(prefix, mf);//prefix
}
Map<ReturnImage, Integer> m = null;
m = GetSource.storageSource(key.getStorageType(), map, userpath, null, setday);
Images img = new Images();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
for (Map.Entry<ReturnImage, Integer> entry : m.entrySet()) {
if(entry.getKey()!=null){
if (key.getStorageType() == 5) {
if (config.getDomain() != null) {
jsonObject.put("imgurls", config.getDomain() +"/"+ entry.getKey().getImgurl());
jsonObject.put("imgnames", entry.getKey().getImgname());
img.setImgurl(config.getDomain() +"/"+ entry.getKey().getImgurl());
} else {
jsonObject.put("imgurls", config.getDomain() +"/"+ entry.getKey().getImgurl());
jsonObject.put("imgnames", entry.getKey().getImgname());
img.setImgurl("http://" + IPPortUtil.getLocalIP() + ":" + IPPortUtil.getLocalPort() +"/"+ entry.getKey().getImgurl());//图片链接
}
} else {
jsonObject.put("imgurls", entry.getKey().getImgurl());
jsonObject.put("imgnames", entry.getKey().getImgname());
img.setImgurl( entry.getKey().getImgurl());
}
jsonArray.add(jsonObject);
img.setUpdatetime(df.format(new Date()));
img.setSource(key.getStorageType());
img.setUserid(u == null ? 0 : u.getId());
img.setSizes((entry.getValue()) / 1024);
if(uploadConfig.getUrltype()==2){
//img.setImgname(SetText.getSubString(entry.getKey().getImgurl(), "", ""));
String[] imgname = entry.getKey().getImgurl().split ("/");
String name = "";
for (int i = 0; i < imgname.length; i++) {
if(i>2 && i!=imgname.length-1){
name+=imgname[i]+"/";
}
if(i==imgname.length-1){
name+=imgname[i];
}
}
img.setImgname(entry.getKey().getImgname());
}else{
img.setImgname(SetText.getSubString(entry.getKey().getImgurl(), key.getRequestAddress() + "/", ""));
}
img.setImgtype(setday > 0 ? 1 : 0);
img.setAbnormal(userip);
img.setMd5key(md5key);
userMapper.insertimg(img);
long etime = System.currentTimeMillis();
Print.Normal("上传图片所用时长:" + String.valueOf(etime - stime) + "ms");
}else{
msg.setCode("5001");
return msg;
}
}
msg.setData(jsonArray);
return msg;
}
public String uploadForURL() {
return "";
}
private Integer yzupdate() {
Calendar cal = Calendar.getInstance();
int y = cal.get(Calendar.YEAR);
int m = cal.get(Calendar.MONTH);
int d = cal.get(Calendar.DATE);
//int h=cal.get(Calendar.HOUR_OF_DAY);
//int mm=cal.get(Calendar.MINUTE);
return y + m + d + 999;
}
}
@@ -26,9 +26,9 @@ public class UserServiceImpl implements UserService {
}
@Override
public Integer login(String email, String password) {
public Integer login(String email, String password,String uid) {
// TODO Auto-generated method stub
return userMapper.login(email, password);
return userMapper.login(email, password,uid);
}
@Override
-81
View File
@@ -1,81 +0,0 @@
package cn.hellohao.test;
import cn.hellohao.utils.Print;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;
/**
* Hello world!
*/
class GetPostTest {
public static String sendGet(String url, String param) {
String result = "";
String urlName = "https://v1.hitokoto.cn/";
try {
URL realURL = new URL(urlName);
URLConnection conn = realURL.openConnection();
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36");
conn.connect();
Map<String, List<String>> map = conn.getHeaderFields();
for (String s : map.keySet()) {
System.out.println(s + "-->" + map.get(s));
}
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
String line;
while ((line = in.readLine()) != null) {
result += "\n" + line;
}
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
public static String sendPost(String url,String param){
String result = "";
try {
URL realUrl = new URL(url);
URLConnection conn = realUrl.openConnection();
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36");
//post设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
PrintWriter out = new PrintWriter(conn.getOutputStream());
out.print(param);
out.flush();
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(),"utf-8"));
String line;
while((line = in.readLine()) != null){
result +="\n" + line;
}
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
public static void main(String[] args) {
Print.warning(GetPostTest.sendGet("",""));
}
}
//public class App {
// public static void main(String[] args) throws Exception {
// System.out.println("hello world");
// String sendRecvGet =GetPostTest.sendGet("http://localhost:8989/testServletEncoding/encodingTest","param=xxxxx嘻嘻嘻");
// System.out.println(sendRecvGet);
// //String sendRecvPost =GetPostTest.sendPost("http://localhost:8989/testServletEncoding/encodingTest","param=就是我");
// //System.out.println(sendRecvPost);
// }
//}
-54
View File
@@ -1,54 +0,0 @@
package cn.hellohao.test;
import cn.hellohao.utils.Print;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import java.io.FileInputStream;
/**
* @author Hellohao
* @version 1.0
* @date 2019/7/29 17:38
* https://blog.csdn.net/WatsonYee/article/details/82389769
*/
public class FTP {
public static void main(String[] args) throws Exception{
//创建FTP客户端,所有的操作都基于FTPClinet
FTPClient ftp = new FTPClient();
//连接FTP服务器
ftp.connect("hellohao.cn",21);
//如果是需要认证的服务器,就需要账号和密码来登录
ftp.login("test", "test");
//获取服务器返回的状态码
int reply = ftp.getReplyCode();
System.out.println(reply);
/*
* 判断是否连接成功
* 所有以2开头的代码是正完成响应。
* FTP服务器将在最终发送一个肯定的完成响应成功完成命令。
*/
if (!FTPReply.isPositiveCompletion(reply)) {
ftp.disconnect();
System.out.println("连接失败");
return;
}
System.out.println("连接成功");
//返回一个布尔类型的值,来表示是否创建成功
boolean isCreate = ftp.makeDirectory("/ftp");
//设置文件上传类型
ftp.setFileType(ftp.BINARY_FILE_TYPE);
//获取文件的输入流
FileInputStream fis = new FileInputStream("C:\\Users\\tiansh\\Desktop\\11.jpg");
//调用storeFile方法将文件上传到FTP服务器
//第一个参数是上传到服务器的路径,包含了文件名
boolean isUpload = ftp.storeFile("/ftp/upload22.jpg", fis);
boolean isUpload2 = ftp.storeFile("/ftp/upload222.jpg", fis);
Print.warning(isUpload+"=="+isUpload2);
Print.Normal(isUpload);
//设置文件权限
boolean isSet = ftp.sendSiteCommand("chmod 744 " + "/ftp/upload.jpg");
//ftp.deleteFile("/ftp/upload.jpg");
}
}
-76
View File
@@ -1,76 +0,0 @@
package cn.hellohao.test;
import cn.hellohao.utils.Print;
import cn.hutool.crypto.SecureUtil;
import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import java.io.*;
import java.security.SecureRandom;
import java.util.Date;
public class test1 {
public static void main(String[] args) throws Exception {
readFile(File.separator + "HellohaoData"+File.separator+"img.ini");
//charu("Hellohao/b3da10930021007.png|");
}
public static void charu(String src) {
String filePath =File.separator + "HellohaoData" ;
File file = new File(filePath);
File file1 = new File(filePath+File.separator+"img.ini");
if(!file.exists()){
file.mkdirs();
}
if(!file1.exists()){
try {
file1.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
FileWriter fw = null;
try {
//如果文件存在,则追加内容;如果文件不存在,则创建文件
fw = new FileWriter(file1, true);
} catch (IOException e) {
e.printStackTrace();
}
PrintWriter pw = new PrintWriter(fw);
pw.println(src);//插入每行的内容
pw.flush();
try {
fw.flush();
pw.close();
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
// 读取文件内容
public static String readFile(String path) {//路径
File file = new File(path);
StringBuilder result = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file), "GBK"));//构造一个BufferedReader类来读取文件
String s = null;
while ((s = br.readLine()) != null) {//使用readLine方法,一次读一行
result.append(System.lineSeparator() + s);
Print.Normal( s);
}
br.close();
} catch (Exception e) {
e.printStackTrace();
}
return result.toString();
}
}
+97 -1
View File
@@ -6,6 +6,10 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import java.io.File;
import java.sql.SQLException;
import java.util.UUID;
/**
* @author Hellohao
* @version 1.0
@@ -29,22 +33,114 @@ public class FirstRun implements InitializingBean {
RunSqlScript.PASSWORD = jdbcpass;
RunSqlScript.DBURL = jdbcurl;
Print.Normal("正在校验数据库参数...");
RunSqlScript.RunInsert(dynamic);
RunSqlScript.RunInsert(compressed);
String uid = UUID.randomUUID().toString().replace("-", "").toLowerCase();
RunSqlScript.RunInsert("update user set uid='"+uid+"' where id = 1");
Integer ret1 = RunSqlScript.RunSelectCount(sql1);
if(ret1==0){
Print.Normal("In execution...");
RunSqlScript.RunInsert(sql2);
;
}else{
if(ret1>0){
Print.Normal("Good! No action required!");
Print.Normal("Stage 1");
}else{
Print.Normal("Mysql 报了一个错");
}
}
Integer imgandalbum = RunSqlScript.RunSelectCount(judgeTable+"'imgandalbum'");
if(imgandalbum==0){
RunSqlScript.RunInsert(sql3);
Print.Normal("Stage 2");
}
Integer album = RunSqlScript.RunSelectCount(judgeTable+"'album'");
if(album==0){
RunSqlScript.RunInsert(sql4);
Print.Normal("Stage 3");
}
Integer ret2 = RunSqlScript.RunSelectCount(judgeTable+"'imgdata' and column_name = 'explains'");
if(ret2==0){
RunSqlScript.RunInsert(sql6);
Print.Normal("Stage 4");
}
Integer ret3 = RunSqlScript.RunSelectCount(judgeTable+"'album' and column_name = 'userid'");
if(ret3==0){
RunSqlScript.RunInsert(sql7);
Print.Normal("Stage 5");
}
Integer ret4 = RunSqlScript.RunSelectCount(judgeTable+"'imgdata' and column_name = 'md5key'");
if(ret4==0){
RunSqlScript.RunInsert(sql8);
Print.Normal("Stage 6");
}
Integer ret5 = RunSqlScript.RunSelectCount(judgeTable+"'config' and column_name = 'theme'");
if(ret5==0){
RunSqlScript.RunInsert(sql9);
Print.Normal("Stage 7");
}
Integer ret6 = RunSqlScript.RunSelectCount(judgeTable+"'imgandalbum' and column_name = 'notes' and TABLE_SCHEMA='picturebed'");
if(ret6==0){
RunSqlScript.RunInsert(sql11);
Print.Normal("Stage 8");
}
RunSqlScript.RunInsert(sql10);
//RunSqlScript.RunInsert("alter table imgdata drop index index_md5key_url");
RunSqlScript.RunInsert(inddx_md5key);
RunSqlScript.RunInsert("UPDATE `keys` SET `Endpoint` = '0' WHERE `id` = 8");
Print.Normal("Stage success");
}
//检查表是否存在,后边加'imgdata' and column_name = 'explains' 检查字段是否存在
private String judgeTable = "select count(*) from information_schema.columns where table_name = ";
//创建blacklist 2019-11-29
private String sql1 = "select count(*) from information_schema.columns where table_name = 'uploadconfig' and column_name = 'blacklist'";
private String sql2 = "alter table uploadconfig add blacklist varchar(500);";
//创建imgandalbum和album 添加imgdata表字段explain 2019-12-20
private String sql3 ="CREATE TABLE `imgandalbum` (`imgname` varchar(5000) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,`albumkey` varchar(5000) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic";
private String sql4 ="CREATE TABLE `album` (`albumkey` varchar(5000) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,`albumtitle` varchar(5000) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,`createdate` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, `password` varchar(5000) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic";
private String sql6 = "alter table imgdata add explains varchar(5000)";
//添加album表字段userid
private String sql7 = "alter table album add userid int(10)";
//添加imgdata表字段md5key
private String sql8 = "alter table imgdata add md5key varchar(5000)";
private String sql9 = "ALTER TABLE config ADD theme int(4) DEFAULT '1' COMMENT '主题' ";
//修改字段长度
private String sql10 = "alter table config modify column `explain` varchar(1000),modify column links varchar(1000),modify column notice varchar(1000),modify column baidu varchar(1000)";
//添加imgandalbum字段notes(添加画廊图片说明)
private String sql11 = "alter table imgandalbum add notes varchar(1000) DEFAULT ' '";
private String inddx_md5key = "ALTER TABLE imgdata ADD INDEX index_md5key_url ( md5key,imgurl)";
// create index yarn_app_result_i4 on yarn_app_result (flow_exec_id(100), another_column(50));
private String dynamic = "alter table imgdata row_format=dynamic";
private String compressed = "alter table imgdata row_format=compressed";
private void clears(){
File file1 = new File(File.separator+"HellohaoData"+File.separator+"hellohaotempimg");
File file2 = new File(File.separator+"HellohaoData"+File.separator+"hellohaotempwatermarimg");
//判断目录有没有创建
File file = new File(File.separator+"HellohaoData");
if(!file.exists()){
file.mkdirs();
file1.mkdirs();
file2.mkdirs();
}else{
if(!file1.exists()){
file1.mkdirs();
}else if(!file2.exists()){
file2.mkdirs();
}
}
}
}
@@ -21,13 +21,14 @@ public class GetSource {
KODOImageupload kodoImageupload = SpringContextHolder.getBean(KODOImageupload.class);
COSImageupload cosImageupload = SpringContextHolder.getBean(COSImageupload.class);
FTPImageupload ftpImageupload = SpringContextHolder.getBean(FTPImageupload.class);
UFileImageupload uFileImageupload = SpringContextHolder.getBean(UFileImageupload.class);
Map<ReturnImage, Integer> m = null;
try {
if(type==1){
m = nosImageupload.Imageupload(fileMap, userpath,filename,setday);
}else if (type==2){
m = ossImageupload.ImageuploadOSS(fileMap, userpath,filename,setday);
}else if(type==3){
}else if(type==3 ){
m = ussImageupload.ImageuploadUSS(fileMap, userpath,filename,setday);
}else if(type==4){
m = kodoImageupload.ImageuploadKODO(fileMap, userpath,filename,setday);
@@ -37,6 +38,8 @@ public class GetSource {
m = cosImageupload.ImageuploadCOS(fileMap, userpath,filename,setday);
}else if(type==7){
m = ftpImageupload.ImageuploadFTP(fileMap, userpath,filename,setday);
}else if(type==8){
m = uFileImageupload.ImageuploadUSS(fileMap, userpath,filename,setday);
}
else{
new StorageSourceInitException("GetSource类捕捉异常:未找到存储源");
@@ -20,10 +20,15 @@ public class IPPortUtil {
* @throws MalformedObjectNameException
* 获取当前机器的端口号
*/
public static String getLocalPort() throws MalformedObjectNameException {
public static String getLocalPort() {//throws MalformedObjectNameException
MBeanServer beanServer = ManagementFactory.getPlatformMBeanServer();
Set<ObjectName> objectNames = beanServer.queryNames(new ObjectName("*:type=Connector,*"),
Query.match(Query.attr("protocol"), Query.value("HTTP/1.1")));
Set<ObjectName> objectNames = null;
try {
objectNames = beanServer.queryNames(new ObjectName("*:type=Connector,*"),
Query.match(Query.attr("protocol"), Query.value("HTTP/1.1")));
} catch (MalformedObjectNameException e) {
e.printStackTrace();
}
String port = objectNames.iterator().next().getKeyProperty("port");
return port;
}
@@ -54,8 +54,6 @@ public class ImgUrlUtil {
* @param savePath
* @throws IOException
*/
public static boolean downLoadFromUrl(String urlStr,String fileName,String savePath) throws IOException{
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
@@ -24,18 +24,20 @@ public class LocUpdateImg {
File file = null;
Map<ReturnImage, Integer> ImgUrl = new HashMap<>();
for (Map.Entry<String, MultipartFile> entry : fileMap.entrySet()) {
String uuid = UUID.randomUUID().toString().replace("-", "").toLowerCase().substring(0,5);//生成一个没有-的uuid,然后取前5位
String uuid = "TOIMG"+UUID.randomUUID().toString().replace("-", "").toLowerCase().substring(0,5);//生成一个没有-的uuid,然后取前5位
java.text.DateFormat format1 = new java.text.SimpleDateFormat("MMddhhmmss");
String times = format1.format(new Date());
// 上传文件流。
System.out.println("待上传的图片:"+username + "/" + uuid+times + "." + entry.getKey());
File dest = new File(filePath + username + File.separator+ uuid+times + "." + entry.getKey());
System.out.println("待上传的图片:"+username + File.separator + uuid+times + "N." + entry.getKey());
File dest = new File(filePath + username + File.separator+ uuid+times + "N." + entry.getKey());
File temppath = new File(filePath + username+ File.separator );
if (!dest.getParentFile().exists()) {
dest.getParentFile().mkdirs();
}
try {
MultipartFile multipartFile = entry.getValue();
FileInputStream fileInputStream = (FileInputStream) multipartFile.getInputStream();
//FileInputStream fileInputStream = (FileInputStream) multipartFile.getInputStream();
InputStream fileInputStream = (InputStream)multipartFile.getInputStream();
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(dest));
byte[] bs = new byte[1024];
int len;
@@ -45,12 +47,12 @@ public class LocUpdateImg {
bos.flush();
bos.close();
ReturnImage returnImage = new ReturnImage();
returnImage.setImgname(entry.getValue().getOriginalFilename());
returnImage.setImgurl(username + "/" + uuid+times + "." + entry.getKey());
returnImage.setImgname(username + "/" +uuid+times + "N." + entry.getKey());//entry.getValue().getOriginalFilename()
returnImage.setImgurl(username + "/" + uuid+times + "N." + entry.getKey());
ImgUrl.put(returnImage, (int) (entry.getValue().getSize()));
if(setday>0) {
String deleimg = DateUtils.plusDay(setday);
DeleImg.charu(username + "/" + uuid + times + "." + entry.getKey() + "|" + deleimg + "|" + "5");
DeleImg.charu(username + "/" + uuid + times + "N." + entry.getKey() + "|" + deleimg + "|" + "5");
}
} catch (IOException e) {
e.printStackTrace();
@@ -61,20 +63,22 @@ public class LocUpdateImg {
}else{
Map<ReturnImage, Integer> ImgUrl = new HashMap<>();
for (Map.Entry<String, String> entry : fileMap2.entrySet()) {
String uuid = UUID.randomUUID().toString().replace("-", "").toLowerCase().substring(0,5);//生成一个没有-的uuid,然后取前5位
String uuid = "TOIMG"+UUID.randomUUID().toString().replace("-", "").toLowerCase().substring(0,5);//生成一个没有-的uuid,然后取前5位
java.text.DateFormat format1 = new java.text.SimpleDateFormat("MMddhhmmss");
String times = format1.format(new Date());
String oldfilePath = entry.getValue();
String newfilePath = File.separator + "HellohaoData" + File.separator + username + File.separator+ uuid+times + "." + entry.getKey();//
String newfilePath = File.separator + "HellohaoData" + File.separator + username + File.separator+ uuid+times + "N." + entry.getKey();
String tempfilePath = File.separator + "HellohaoData" + File.separator + username+ File.separator ;
File file = new File(oldfilePath);
File targetFile =new File(newfilePath);
File targetFile =new File(tempfilePath);
if(!targetFile.getParentFile().exists()) {
targetFile.mkdirs();
}
file.renameTo(new File(newfilePath));
// 例2采用数据流模式上传文件(节省内存),自动创建父级目录
//采用数据流模式上传文件(节省内存),自动创建父级目录
ReturnImage returnImage = new ReturnImage();
returnImage.setImgurl(username + "/" + uuid+times + "." + entry.getKey());
//username + "/" + uuid+times + "." + entry.getKey()
returnImage.setImgurl(username + "/" + uuid+times + "N." + entry.getKey());
ImgUrl.put( returnImage, ImgUrlUtil.getFileSize2(new File(newfilePath)));
if(setday>0) {
String deleimg = DateUtils.plusDay(setday);
@@ -88,18 +92,18 @@ public class LocUpdateImg {
/**
* 客户端接口
* */
public static Map<ReturnImage, Integer> clientuploadFTP(Map<String, MultipartFile> fileMap, String username, UploadConfig uploadConfig) {
public static Map<ReturnImage, Integer> clientLocUpdateImg(Map<String, MultipartFile> fileMap, String username, UploadConfig uploadConfig) {
String filePath =File.separator + "HellohaoData" + File.separator;
File file = null;
Map<ReturnImage, Integer> ImgUrl = new HashMap<>();
for (Map.Entry<String, MultipartFile> entry : fileMap.entrySet()) {
String uuid = UUID.randomUUID().toString().replace("-", "").toLowerCase().substring(0,5);//生成一个没有-的uuid,然后取前5位
String uuid = "TOIMG"+UUID.randomUUID().toString().replace("-", "").toLowerCase().substring(0,5);//生成一个没有-的uuid,然后取前5位
java.text.DateFormat format1 = new java.text.SimpleDateFormat("MMddhhmmss");
String times = format1.format(new Date());
System.out.println("待上传的图片:"+username + "/" + uuid+times + "." + entry.getKey());
System.out.println("待上传的图片:"+username + "/" + uuid+times + "N." + entry.getKey());
ReturnImage returnImage = new ReturnImage();
if(entry.getValue().getSize()/1024<=uploadConfig.getFilesizeuser()*1024){
File dest = new File(filePath + username + File.separator+ uuid+times + "." + entry.getKey());
File dest = new File(filePath + username + File.separator+ uuid+times + "N." + entry.getKey());
if (!dest.getParentFile().exists()) {
dest.getParentFile().mkdirs();
}
@@ -115,8 +119,8 @@ public class LocUpdateImg {
bos.flush();
bos.close();
returnImage.setImgname(entry.getValue().getOriginalFilename());
returnImage.setImgurl(username + "/" + uuid+times + "." + entry.getKey());
ImgUrl.put(returnImage, (int) (entry.getValue().getSize()));
returnImage.setImgurl(username + "/" + uuid+times + "N." + entry.getKey());
ImgUrl.put(returnImage, (int) (entry.getValue().getSize())/1024);
} catch (IOException e) {
e.printStackTrace();
System.err.println("上传失败");
+48 -5
View File
@@ -2,18 +2,61 @@ package cn.hellohao.utils;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.*;
public class SetFiles {
// 转换文件方法
public static File changeFile(MultipartFile multipartFile) throws Exception {
public static File changeFile(MultipartFile multipartFile) {
// 获取文件名
String fileName = multipartFile.getOriginalFilename();
String fileName = multipartFile.getName();//multipartFile.getOriginalFilename();
// 获取文件后缀
String prefix = fileName.substring(fileName.lastIndexOf("."));
// todo 修改临时文件文件名
File file = File.createTempFile(fileName, prefix);
multipartFile.transferTo(file);
File file = null;
try {
file = File.createTempFile(fileName, prefix);
multipartFile.transferTo(file);
} catch (IOException e) {
e.printStackTrace();
}
return file;
}
public static File changeFile_c(MultipartFile multipartFile) {
// 获取文件名
String fileName = multipartFile.getOriginalFilename();//multipartFile.getOriginalFilename();
// 获取文件后缀
String prefix = fileName.substring(fileName.lastIndexOf("."));
// todo 修改临时文件文件名
File file = null;
try {
file = File.createTempFile(fileName, prefix);
multipartFile.transferTo(file);
} catch (IOException e) {
e.printStackTrace();
}
return file;
}
// 转换文件方法
public static File changeFile_new(MultipartFile multipartFile) {
// 获取文件名
String fileName = multipartFile.getOriginalFilename();//getOriginalFilename
// 获取文件后缀
String prefix = fileName.substring(fileName.lastIndexOf("."));
// todo 修改临时文件文件名
File file = null;
try {
file = File.createTempFile(fileName, prefix);
multipartFile.transferTo(file);
} catch (IOException e) {
e.printStackTrace();
}
return file;
}
}
@@ -76,7 +76,7 @@ final class RunSqlScript {
try {
Class.forName(DBDRIVER);
} catch (ClassNotFoundException e) {
e.printStackTrace();
Print.Normal("SqlHelper.java - ClassNotFoundException");
}
//2、连接数据库
//通过连接管理器连接数据库
@@ -84,25 +84,29 @@ final class RunSqlScript {
//在连接的时候直接输入用户名和密码才可以连接
conn = DriverManager.getConnection(DBURL,USERNAME,PASSWORD);
} catch (SQLException e) {
e.printStackTrace();
Print.Normal("SqlHelper.java - SQLException1");
}
try {
stmt = conn.createStatement();
} catch (SQLException e) {
e.printStackTrace();
Print.Normal("SqlHelper.java - SQLException2");
}
//4、执行语句
try {
count = stmt.executeUpdate(sql);
} catch (SQLException e) {
e.printStackTrace();
if(e.getMessage().contains("Duplicate key name") && e.getMessage().contains("index_md5key_url")){
Print.Normal("Database index already exists, skip this step.");
}else{
e.printStackTrace();
}
}
//5、关闭操作
try {
stmt.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
Print.Normal("SqlHelper.java - SQLException4");
}
return count;
}
@@ -7,6 +7,7 @@ import java.util.Collection;
import java.util.Map;
public class StringUtils {
//此方法目前未使用2020-04-06
public static Boolean doNull(Integer sourcekey,Keys k) {
if(sourcekey==1){
if(k.getEndpoint()!=null && k.getAccessSecret()!=null && k.getEndpoint()!=null
+19 -1
View File
@@ -1,5 +1,10 @@
package cn.hellohao.utils;
import javax.imageio.ImageIO;
import java.awt.*;
import java.io.File;
import java.io.IOException;
public class TypeDict {
/**
常用文件的文件头如下:(以前六位为准)
@@ -43,9 +48,22 @@ MIDI (mid),文件头:4D546864
case "474946": return "jif";
case "47494638": return "gif";
case "424D": return "bmp";
case "424D36": return "bmp";
default: return "0000";
}
}
public static Boolean checkImgType(File file) {
try {
// 通过ImageReader来解码这个file并返回一个BufferedImage对象
// 如果找不到合适的ImageReader则会返回null,我们可以认为这不是图片文件
// 或者在解析过程中报错,也返回false
Image image = ImageIO.read(file);
return image != null;
} catch(IOException ex) {
return false;
}
}
}
-146
View File
@@ -1,146 +0,0 @@
package cn.hellohao.utils;
import jdk.nashorn.internal.objects.annotations.Where;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.multipart.MultipartFile;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
/**
* @author Hellohao
* @version 1.0
* @date 2019/10/11 17:26
*/
public class demo {
/**
* 向指定 URL 发送POST方法的请求
*
* @param url
* 发送请求的 URL
* @param string
* 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
* @return 所代表远程资源的响应结果
*/
public static String sendPost(String url, String string,Integer i) {
String intFlag = String.valueOf((int)(Math.random() * 1000000));
PrintWriter out = null;
BufferedReader in = null;
String result = "";
try {
URL realUrl = new URL(url);
// 打开和URL之间的连接
URLConnection conn = realUrl.openConnection();
// 设置通用的请求属性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
// 获取URLConnection对象对应的输出流
out = new PrintWriter(conn.getOutputStream());
// 发送请求参数
out.print(string);
// flush输出流的缓冲
out.flush();
// 定义BufferedReader输入流来读取URL的响应
in = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println("发送 POST 请求出现异常!"+e);
e.printStackTrace();
}
//使用finally块来关闭输出流、输入流
finally{
try{
if(out!=null){
out.close();
}
if(in!=null){
in.close();
}
}
catch(IOException ex){
ex.printStackTrace();
}
}
System.out.println("已成功执行"+i+"");
return result;
}
//文件上传
public static String uploadFileToOSS(MultipartFile multfile,String isurl) {
CloseableHttpClient client = null;
String result = null;
try {
client = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(isurl);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
//addTextBody(String,String)该方法可以传入参数,例如请求的地址需要接受一个id
//builder.addTextBody("id", "1");
// builder.addTextBody("arg", "value");
//addBinaryBody()该方法传入二进制内容,可以传入InputStream,File, 参数三是传入的类型,参数四是文件名称
builder.addBinaryBody("file", multfile.getInputStream(), ContentType.MULTIPART_FORM_DATA, "1.png");
httpPost.setEntity(builder.build());
HttpResponse response = client.execute(httpPost);
if (response.getStatusLine().getStatusCode() == 200) {
// 取回服务器端的响应结果
result = EntityUtils.toString(response.getEntity(), "utf-8");
}
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
client.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
public static void main(String[] args)throws Exception {
File file = new File("D:/22.png");
// for(int i=1;i<99999999;i++){
// String intFlag = String.valueOf((int)(Math.random() * 1000000));
// //sendPost("http://shenhhh.net/index.php?m=User&a=signup","phone=13232"+intFlag+"&password=asd"+intFlag+"",i);
// //String ret = sendPost("https://test.demo-1s.com/register","name=jbb"+intFlag+"&email=jbb"+intFlag+"@jbb.com&password=jbb"+intFlag,i);
//
// String ret = sendPost("https://www.png8.com/upload/localhost","file="+file,i);
// System.out.println("账号:goto"+intFlag+"-- 密码:baa"+intFlag+"-- 邮箱:jbb"+intFlag+"@jbb.com -- 返回值:"+ret);
// }
//文件上传
//while (true){
FileInputStream fileInputStream = new FileInputStream(file);
MultipartFile multipartFile = new MockMultipartFile(file.getName(), file.getName(),
ContentType.APPLICATION_OCTET_STREAM.toString(), fileInputStream);
String a =uploadFileToOSS(multipartFile ,"https://tu.sunpma.com/upload/localhost");
System.out.println("");
Print.Normal(""+a+"");
System.out.println("");
}
// }
}
+22 -7
View File
@@ -6,26 +6,41 @@ spring.datasource.password=root
spring.datasource.url=jdbc:mysql://localhost:3306/picturebed?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8
#端口
server.port=8088
#鉴黄周期表达式 下方表达式为每天点半执行
#不懂请勿乱修改。具体可以参考官方文档http://doc.wwery.com
#鉴黄周期表达式 下方表达式为每天点半执行0 30 04 * * ?
Expression=0 30 04 * * ?
#下边的配置项不需要修改。
logging.config=classpath:logback-spring.xml
logging.file.path=/HellohaoData/tbedlog
spring.thymeleaf.suffix=.html
mybatis.configuration.map-underscore-to-camel-case=true
mybatis.mapper-locations=classpath:mapper/*.xml
logging.level.cn.hellohao.dao=debug
#logging.level.cn.hellohao.dao=debug
spring.jackson.date-format=yyyy-MM-dd HH:mm:ss
spring.jackson.time-zone=GMT+8
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.thymeleaf.cache=false
multipart.maxFileSize=10240KB
multipart.maxRequestSize=10240KB
spring.thymeleaf.mode = LEGACYHTML5
spring.http.multipart.location=/data/upload_tmp
systemupdate=2019-11-29
systemupdate=2020-05-26
spring.datasource.druid.filter.config.enabled=false
spring.datasource.druid.web-stat-filter.enabled=false
spring.datasource.druid.web-stat-filter.session-stat-enable=false
spring.datasource.druid.stat-view-servlet.reset-enable=false
spring.datasource.druid.filter.stat.enabled=false
spring.datasource.druid.filter.wall.enabled=false
spring.datasource.druid.filter.slf4j.enabled=false
spring.datasource.druid.filter.log4j2.enabled=false
spring.datasource.druid.filter.log4j.enabled=false
spring.datasource.druid.filter.commons-log.enabled=false
spring.datasource.druid.stat-view-servlet.enabled=false
spring.datasource.druid.stat-view-servlet.login-username=hellohao@dealer
spring.datasource.druid.stat-view-servlet.login-password=52BNmXPJL0rQQ3CU
spring.datasource.druid.stat-view-servlet.allow=127.0.0.1
spring.datasource.druid.web-stat-filter.exclusions=false
+197
View File
@@ -0,0 +1,197 @@
<?xml version="1.0" encoding="UTF-8"?>
<!-- 日志级别从低到高分为TRACE < DEBUG < INFO < WARN < ERROR < FATAL,如果设置为WARN,则低于WARN的信息都不会输出 -->
<!-- scan:当此属性设置为true时,配置文件如果发生改变,将会被重新加载,默认值为true -->
<!-- scanPeriod:设置监测配置文件是否有修改的时间间隔,如果没有给出时间单位,默认单位是毫秒。当scan为true时,此属性生效。默认的时间间隔为1分钟。 -->
<!-- debug:当此属性设置为true时,将打印出logback内部日志信息,实时查看logback运行状态。默认值为false。 -->
<configuration scan="true" scanPeriod="10 seconds">
<!--<include resource="org/springframework/boot/logging/logback/base.xml" />-->
<contextName>logback</contextName>
<!-- name的值是变量的名称,value的值时变量定义的值。通过定义的值会被插入到logger上下文中。定义变量后,可以使“${}”来使用变量。 -->
<property name="log.path" value="/HellohaoData/tbedlog" />
<!-- 彩色日志 -->
<!-- 彩色日志依赖的渲染类 -->
<conversionRule conversionWord="clr" converterClass="org.springframework.boot.logging.logback.ColorConverter" />
<conversionRule conversionWord="wex" converterClass="org.springframework.boot.logging.logback.WhitespaceThrowableProxyConverter" />
<conversionRule conversionWord="wEx" converterClass="org.springframework.boot.logging.logback.ExtendedWhitespaceThrowableProxyConverter" />
<!-- 彩色日志格式 -->
<property name="CONSOLE_LOG_PATTERN" value="${CONSOLE_LOG_PATTERN:-%clr(%d{yyyy-MM-dd HH:mm:ss.SSS}){faint} %clr(${LOG_LEVEL_PATTERN:-%5p}) %clr(${PID:- }){magenta} %clr(---){faint} %clr([%15.15t]){faint} %clr(%-40.40logger{39}){cyan} %clr(:){faint} %m%n${LOG_EXCEPTION_CONVERSION_WORD:-%wEx}}"/>
<!--输出到控制台-->
<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
<!--此日志appender是为开发使用,只配置最底级别,控制台输出的日志级别是大于或等于此级别的日志信息-->
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
<level>DEBUG</level>
</filter>
<encoder>
<Pattern>${CONSOLE_LOG_PATTERN}</Pattern>
<!-- 设置字符集 -->
<charset>UTF-8</charset>
</encoder>
</appender>
<!--输出到文件-->
<!-- 时间滚动输出 level为 DEBUG 日志 -->
<appender name="DEBUG_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<!-- 正在记录的日志文件的路径及文件名 -->
<file>${log.path}/log_debug.log</file>
<!--日志文件输出格式-->
<encoder>
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
<charset>UTF-8</charset> <!-- 设置字符集 -->
</encoder>
<!-- 日志记录器的滚动策略,按日期,按大小记录 -->
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!-- 日志归档 -->
<fileNamePattern>${log.path}/debug/log-debug-%d{yyyy-MM-dd}.%i.log</fileNamePattern>
<timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
<maxFileSize>100MB</maxFileSize>
</timeBasedFileNamingAndTriggeringPolicy>
<!--日志文件保留天数-->
<maxHistory>15</maxHistory>
</rollingPolicy>
<!-- 此日志文件只记录debug级别的 -->
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>debug</level>
<onMatch>ACCEPT</onMatch>
<onMismatch>DENY</onMismatch>
</filter>
</appender>
<!-- 时间滚动输出 level为 INFO 日志 -->
<appender name="INFO_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<!-- 正在记录的日志文件的路径及文件名 -->
<file>${log.path}/log_info.log</file>
<!--日志文件输出格式-->
<encoder>
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
<charset>UTF-8</charset>
</encoder>
<!-- 日志记录器的滚动策略,按日期,按大小记录 -->
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!-- 每天日志归档路径以及格式 -->
<fileNamePattern>${log.path}/info/log-info-%d{yyyy-MM-dd}.%i.log</fileNamePattern>
<timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
<maxFileSize>100MB</maxFileSize>
</timeBasedFileNamingAndTriggeringPolicy>
<!--日志文件保留天数-->
<maxHistory>15</maxHistory>
</rollingPolicy>
<!-- 此日志文件只记录info级别的 -->
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>info</level>
<onMatch>ACCEPT</onMatch>
<onMismatch>DENY</onMismatch>
</filter>
</appender>
<!-- 时间滚动输出 level为 WARN 日志 -->
<appender name="WARN_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<!-- 正在记录的日志文件的路径及文件名 -->
<file>${log.path}/log_warn.log</file>
<!--日志文件输出格式-->
<encoder>
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
<charset>UTF-8</charset> <!-- 此处设置字符集 -->
</encoder>
<!-- 日志记录器的滚动策略,按日期,按大小记录 -->
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>${log.path}/warn/log-warn-%d{yyyy-MM-dd}.%i.log</fileNamePattern>
<timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
<maxFileSize>100MB</maxFileSize>
</timeBasedFileNamingAndTriggeringPolicy>
<!--日志文件保留天数-->
<maxHistory>15</maxHistory>
</rollingPolicy>
<!-- 此日志文件只记录warn级别的 -->
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>warn</level>
<onMatch>ACCEPT</onMatch>
<onMismatch>DENY</onMismatch>
</filter>
</appender>
<!-- 时间滚动输出 level为 ERROR 日志 -->
<appender name="ERROR_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<!-- 正在记录的日志文件的路径及文件名 -->
<file>${log.path}/log_error.log</file>
<!--日志文件输出格式-->
<encoder>
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
<charset>UTF-8</charset> <!-- 此处设置字符集 -->
</encoder>
<!-- 日志记录器的滚动策略,按日期,按大小记录 -->
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>${log.path}/error/log-error-%d{yyyy-MM-dd}.%i.log</fileNamePattern>
<timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
<maxFileSize>100MB</maxFileSize>
</timeBasedFileNamingAndTriggeringPolicy>
<!--日志文件保留天数-->
<maxHistory>15</maxHistory>
</rollingPolicy>
<!-- 此日志文件只记录ERROR级别的 -->
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>ERROR</level>
<onMatch>ACCEPT</onMatch>
<onMismatch>DENY</onMismatch>
</filter>
</appender>
<!--
<logger>用来设置某一个包或者具体的某一个类的日志打印级别、
以及指定<appender>。<logger>仅有一个name属性,
一个可选的level和一个可选的addtivity属性。
name:用来指定受此logger约束的某一个包或者具体的某一个类。
level:用来设置打印级别,大小写无关:TRACE, DEBUG, INFO, WARN, ERROR, ALL 和 OFF
还有一个特俗值INHERITED或者同义词NULL,代表强制执行上级的级别。
如果未设置此属性,那么当前logger将会继承上级的级别。
addtivity:是否向上级logger传递打印信息。默认是true。
-->
<!--<logger name="org.springframework.web" level="info"/>-->
<!--<logger name="org.springframework.scheduling.annotation.ScheduledAnnotationBeanPostProcessor" level="INFO"/>-->
<!--
使用mybatis的时候,sql语句是debug下才会打印,而这里我们只配置了info,所以想要查看sql语句的话,有以下两种操作:
第一种把<root level="info">改成<root level="DEBUG">这样就会打印sql,不过这样日志那边会出现很多其他消息
第二种就是单独给dao下目录配置debug模式,代码如下,这样配置sql语句会打印,其他还是正常info级别:
-->
<!--
root节点是必选节点,用来指定最基础的日志输出级别,只有一个level属性
level:用来设置打印级别,大小写无关:TRACE, DEBUG, INFO, WARN, ERROR, ALL 和 OFF
不能设置为INHERITED或者同义词NULL。默认是DEBUG
可以包含零个或多个元素,标识这个appender将会添加到这个logger。
-->
<!--开发环境:打印控制台-->
<springProfile name="dev">
<logger name="cn.hellohao.dao" level="debug"/>
</springProfile>
<root level="info">
<appender-ref ref="CONSOLE" />
<appender-ref ref="DEBUG_FILE" />
<appender-ref ref="INFO_FILE" />
<appender-ref ref="WARN_FILE" />
<appender-ref ref="ERROR_FILE" />
</root>
<!--生产环境:输出到文件-->
<!--<springProfile name="pro">-->
<!--<root level="info">-->
<!--<appender-ref ref="CONSOLE" />-->
<!--<appender-ref ref="DEBUG_FILE" />-->
<!--<appender-ref ref="INFO_FILE" />-->
<!--<appender-ref ref="ERROR_FILE" />-->
<!--<appender-ref ref="WARN_FILE" />-->
<!--</root>-->
<!--</springProfile>-->
</configuration>
+55
View File
@@ -0,0 +1,55 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.hellohao.dao.AlbumMapper">
<select id="selectAlbum" parameterType="cn.hellohao.pojo.Album" resultType="cn.hellohao.pojo.Album">
SELECT
*
FROM
`album`
<where>
<if test="albumkey != null">
`albumkey` = #{albumkey}
</if>
<if test="userid != null">
`userid` = #{userid}
</if>
</where>
</select>
<insert id="addAlbum" parameterType="cn.hellohao.pojo.Album">
insert into `album` (albumkey,albumtitle,createdate,`password`,userid)
values (#{albumkey},#{albumtitle},#{createdate},#{password},#{userid})
</insert>
<delete id="deleteAlbum" parameterType="string">
delete from album where albumkey=#{albumkey}
</delete>
<select id="selectAlbumURLList" parameterType="cn.hellohao.pojo.Album" resultType="cn.hellohao.pojo.Album">
SELECT
a.albumkey,
a.albumtitle,
a.createdate,
a.`password`,
a.userid,
u.username
FROM `album` a LEFT JOIN user u on a.userid = u.id
<where>
<if test="albumkey != null">
`albumkey` like '%${albumkey}%'
</if>
<if test="username != null">
`username` like '%${username}%'
</if>
<if test="userid != null">
a.userid = #{userid}
</if>
</where>
order by a.createdate
</select>
</mapper>
@@ -57,6 +57,10 @@
<if test="webfavicons != null">
`webfavicons` = #{webfavicons},
</if>
<if test="theme != null">
`theme` = #{theme},
</if>
</set>
@@ -1,18 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.hellohao.dao.DomainMapper">
<select id="getDomain" parameterType="string" resultType="integer">
SELECT
count(domain)
FROM
`domain`
where 1=1
<if test="domain != null">
and `domain` = #{domain}
</if>
</select>
</mapper>
@@ -0,0 +1,49 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.hellohao.dao.ImgAndAlbumMapper">
<select id="selectImgAndAlbum" parameterType="string" resultType="cn.hellohao.pojo.ImgAndAlbum">
SELECT
*
FROM
`imgandalbum`
<where>
<if test="albumkey != null">
`albumkey` = #{albumkey}
</if>
</where>
</select>
<select id="getAlbumForImgname" resultType="cn.hellohao.pojo.ImgAndAlbum" parameterType="string">
SELECT
*
FROM
`imgandalbum`
<where>
<if test="imgname != null">
`imgname` = #{imgname}
</if>
</where>
</select>
<insert id="addImgAndAlbum" parameterType="cn.hellohao.pojo.ImgAndAlbum">
insert into `imgandalbum` (imgname,albumkey,notes) values (#{imgname},#{albumkey},#{notes})
</insert>
<delete id="deleteImgAndAlbum" parameterType="string">
delete from imgandalbum where imgname=#{imgname}
</delete>
<delete id="deleteImgAndAlbumForKey" parameterType="string">
delete from imgandalbum where albumkey=#{albumkey}
</delete>
<select id="selectImgForAlbumkey" parameterType="string" resultType="cn.hellohao.pojo.Images">
select * from imgdata a
LEFT JOIN imgandalbum b on a.imgname = b.imgname
LEFT JOIN album c on b.albumkey = c.albumkey
where b.albumkey = #{albumkey}
</select>
</mapper>
+50 -12
View File
@@ -13,29 +13,42 @@
a.sizes,
a.abnormal,
a.source,
a.imgtype
a.imgtype,
a.explains,
a.md5key
FROM
imgdata a
LEFT JOIN user b ON a.userid = b.id
where
1=1
<if test="userid != null">
and
userid = #{userid}
</if>
<if test="source != null">
and
source = #{source}
a.source = #{source}
</if>
<if test="starttime != null">
and
updatetime &gt;= #{starttime}
a.updatetime &gt;= #{starttime}
</if>
<if test="stoptime != null">
and
updatetime &lt;= #{stoptime}
a.updatetime &lt;= #{stoptime}
</if>
order by id desc
<if test="userid != null">
<choose>
<when test="selecttype != null">
and
a.userid not in (#{userid})
</when>
<otherwise>
and
a.userid = #{userid}
</otherwise>
</choose>
</if>
order by a.id desc
</select>
<!-- 此用户下总数 -->
<select id="countimg" parameterType="integer" resultType="integer">
@@ -60,8 +73,17 @@
</select>
<!-- 根据图片名字标记IP -->
<update id="setabnormal" parameterType="string">
UPDATE imgdata set abnormal=#{abnormal} where imgname=#{imgname}
<update id="setImg" parameterType="cn.hellohao.pojo.Images">
UPDATE imgdata
<set>
<if test="abnormal!=null">
abnormal=#{abnormal}
</if>
<if test="explains!=null">
explains=#{explains}
</if>
</set>
where imgname=#{imgname}
</update>
<!-- 非法图片删除他 根据名称-->
<delete id="deleimgname" parameterType="string">
@@ -78,7 +100,23 @@
</select>
<!--查询指定用户总内存-->
<select id="getusermemory" parameterType="integer" resultType="integer">
SELECT sum(sizes) FROM `imgdata` where userid = #{userid}
SELECT sum(sizes) as sizes FROM `imgdata` where userid = #{userid}
</select>
<select id="md5Count" resultType="integer">
select count(*) from imgdata
<where>
1=1
<if test="md5key != null">
and md5key=#{md5key}
</if>
</where>
</select>
<select id="selectImgUrlByMD5" parameterType="string" resultType="cn.hellohao.pojo.Images">
select imgname,imgurl from imgdata where md5key = #{md5key}
</select>
</mapper>
+1 -1
View File
@@ -2,7 +2,7 @@
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.hellohao.dao.NoticeMapper">
<select id="getNotice" resultType="string">
select text from Notice where id = 1
select text from notice where id = 1
</select>
</mapper>
+18 -4
View File
@@ -18,6 +18,7 @@
select COUNT(*)
from user
where email = #{email}
</select>
<!-- uid查询用户并修改 -->
<update id="uiduser" parameterType="cn.hellohao.pojo.User">
@@ -29,8 +30,21 @@
<select id="login" parameterType="string" resultType="integer">
select COUNT(*)
from user
where email = #{email}
and password = #{password}
<!-- where email = #{email}-->
<!-- and password = #{password}-->
<where>
1=1
<if test="email != null">
and email = #{email}
</if>
<if test="password != null">
and password = #{password}
</if>
<if test="uid != null">
and uid = #{uid}
</if>
</where>
</select>
<!-- 查询当前用户:根据邮箱 -->
@@ -81,8 +95,8 @@
<!-- 插入图片信息 -->
<insert id="insertimg" parameterType="cn.hellohao.pojo.Images">
INSERT INTO imgdata (id, imgname, imgurl, userid, updatetime,sizes,abnormal,source,imgtype)
VALUES (NULL, #{imgname}, #{imgurl}, #{userid}, #{updatetime},#{sizes},#{abnormal},#{source},#{imgtype})
INSERT INTO imgdata (id, imgname, imgurl, userid, updatetime,sizes,abnormal,source,imgtype,md5key)
VALUES (NULL, #{imgname}, #{imgurl}, #{userid}, #{updatetime},#{sizes},#{abnormal},#{source},#{imgtype},#{md5key})
</insert>
<!-- 修改资料 -->
+5 -3
View File
@@ -2,12 +2,14 @@
<!--
This is the JRebel configuration file. It maps the running application to your IDE workspace, enabling JRebel reloading for this project.
Refer to https://manuals.zeroturnaround.com/jrebel/standalone/config.html for more information.
Refer to https://manuals.jrebel.com/jrebel/standalone/config.html for more information.
-->
<application generated-by="intellij" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.zeroturnaround.com" xsi:schemaLocation="http://www.zeroturnaround.com http://update.zeroturnaround.com/jrebel/rebel-2_1.xsd">
<application generated-by="intellij" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.zeroturnaround.com" xsi:schemaLocation="http://www.zeroturnaround.com http://update.zeroturnaround.com/jrebel/rebel-2_3.xsd">
<id>Tbed</id>
<classpath>
<dir name="D:/Data/project/myjavawork/Tbed/target/classes">
<dir name="D:/Data/mypoject/Tbed/target/classes">
</dir>
</classpath>
@@ -0,0 +1,35 @@
@charset "utf-8";
/* CSS Document */
/*Reset*/
*{box-sizing:content-box;}
a:hover, a:focus{text-decoration:none;}
body,div,dl,dt,dd,ul,ol,li,h1,h2,h3,h4,h5,h6,pre,form,fieldset,input,textarea,p,blockquote,th,td{margin:0;padding:0;}
table{border-collapse:collapse;border-spacing:0;}
body{-webkit-text-size-adjust:none;}
fieldset,img{border:0;}
img{ vertical-align: top; max-width: 100%; }
address,caption,cite,code,dfn,em,th,var{font-style:normal;font-weight:normal;}
ol,ul{list-style:none;}
caption,th{text-align:left;}
h1,h2,h3,h4,h5,h6{font-size:100%;font-weight:normal;}
q:before,q:after{content:'';}
abbr,acronym {border:0;}
.clearfix:after{visibility:hidden;display: block;font-size:0;content:" ";clear:both;height:0;}
* html .clearfix{ zoom: 1; } /* IE6 */
*:first-child+html .clearfix { zoom: 1; } /* IE7 */
.cli{ clear:both; font-size:0; height:0; overflow:hidden;display:block;}
.lclear{clear:left;font-size:0;height:0;overflow:hidden;}
.fl{float:left;}
.fr{float:right;}
/* ֹ
iframe{nifm2:expression(this.src='about:blank',this.outerHTML='');}
script{no2js:expression((this.src.toLowerCase().indexOf('http')==0)?document.close():'');}
*/
/* ıԼ˶
div{word-wrap: break-word;word-break: normal;}
p{text-align:justify; text-justify:inter-ideograph;}
*/
/*general*/
body{font-size:12px;font-family:'微软雅黑',"宋体","Arial Narrow",Helvetica,sans-serif;color:#000;line-height:1.2;text-align:left;}
a{color:#333;text-decoration:none;}
@@ -0,0 +1,113 @@
html,body{
width:100%;
height:100%;
}
canvas{
display:block;
vertical-align:bottom;
}
.count-particles{
background: #000022;
position: absolute;
top: 48px;
left: 0;
width: 80px;
color: #13E8E9;
font-size: .8em;
text-align: left;
text-indent: 4px;
line-height: 14px;
padding-bottom: 2px;
font-family: Helvetica, Arial, sans-serif;
font-weight: bold;
}
.js-count-particles{
font-size: 1.1em;
}
#stats,
.count-particles{
-webkit-user-select: none;
margin-top: 5px;
margin-left: 5px;
}
#stats{
border-radius: 3px 3px 0 0;
overflow: hidden;
}
.count-particles{
border-radius: 0 0 3px 3px;
}
/* #particles-js{
width: 100%;
height: 100%;
position: relative;
background-image: url(../img/bg.jpg);
background-position: 50% 50%;
background-size: cover;
background-repeat: no-repeat;
margin-left: auto;
margin-right: auto;
} */
.sk-rotating-plane {
display: none;
width: 80px;
height: 80px;
margin: auto;
background-color: white;
-webkit-animation: sk-rotating-plane 1.2s infinite ease-in-out;
animation: sk-rotating-plane 1.2s infinite ease-in-out;
z-index: 1;
position: absolute;
top: 50%;
left: 50%;
margin-left: -40px;
margin-top: -80px;
}
.sk-rotating-plane.active{display: block;}
@keyframes sk-rotating-plane{
0% {
-webkit-transform: perspective(120px) rotateX(0deg) rotateY(0deg);
transform: perspective(120px) rotateX(0deg) rotateY(0deg);
}
50% {
-webkit-transform: perspective(120px) rotateX(-180.1deg) rotateY(0deg);
transform: perspective(120px) rotateX(-180.1deg) rotateY(0deg);
}
100% {
-webkit-transform: perspective(120px) rotateX(-180deg) rotateY(-179.9deg);
transform: perspective(120px) rotateX(-180deg) rotateY(-179.9deg);
}
}
@keyframes login-small{
0%{
transform: scale(1);-moz-transform: scale(1); /* Firefox 4 */-webkit-transform: scale(1); /* Safari 和 Chrome */-o-transform: scale(1); /* Opera */-ms-transform:scale(1); /* IE 9 */
}
100%{
transform: scale(0.2);-moz-transform: scale(0.1); /* Firefox 4 */-webkit-transform: scale(0.2); /* Safari 和 Chrome */-o-transform: scale(0.1); /* Opera */-ms-transform:scale(0.1); /* IE 9 */
}
}
.login{z-index: 2;position:absolute;width: 350px;border-radius: 5px;height: 500px;background: white;box-shadow: 0px 0px 5px #333333;top: 50%;left: 50%;margin-top: -250px;margin-left: -175px;transition: all 1s;-moz-transition: all 1s; /* Firefox 4 */-webkit-transition: all 1s; /* Safari 和 Chrome */-o-transition: all 1s; /* Opera */}
.login-top{font-size: 24px;margin-top: 100px;padding-left: 40px;box-sizing: border-box;color: #333333;margin-bottom: 50px;}
.login-center{width: 100%;box-sizing: border-box;padding: 0 40px;margin-bottom: 30px;}
.login-center-img{width: 20px;height: 20px;float: left;margin-top: 5px;}
.login-center-img>img{width: 100%;}
.login-center-input{float: left;width: 265px/*230px*/;margin-left: 0px;height: 30px;position: relative;}
.login-center-input input{z-index: 2;transition: all 0.5s;padding-left: 10px;color: #333333;width: 105%;height: 30px;border: 0;border-bottom: 1px solid #cccccc;border-top: 1px solid #ffffff;border-left: 1px solid #ffffff;border-right: 1px solid #ffffff;box-sizing: border-box;outline: none;position: relative;}
.login-center-input input:focus{border: 1px solid dodgerblue;}
.login-center-input-text{background: white;padding: 0 5px;position: absolute;z-index: 0;opacity: 0;height: 20px;top: 50%;margin-top: -10px;font-size: 14px;left: 5px;color: dodgerblue;line-height: 20px;transition: all 0.5s;-moz-transition: all 0.5s; /* Firefox 4 */-webkit-transition: all 0.5s; /* Safari 和 Chrome */-o-transition: all 0.5s; /* Opera */}
.login-center-input input:focus~.login-center-input-text{top: 0;z-index: 3;opacity: 1;margin-top: -15px;}
.login.active{-webkit-animation: login-small 0.8s ; animation: login-small 0.8s ;animation-fill-mode:forwards;-webkit-animation-fill-mode:forwards}
.login-button{cursor: pointer;width: 250px;text-align: center;height: 40px;line-height: 40px;background-color: dodgerblue;border-radius: 5px;margin: 0 auto;margin-top: 50px;color: white;}
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because it is too large Load Diff
+2 -1
View File
@@ -1,6 +1,7 @@
body{
background-color:gray;
background-color:#FFF;
/*background: #5583EE;background: -moz-linear-gradient(right, #5583EE 0%, #41D8DD 100%);background: -webkit-linear-gradient(right, #5583EE 0%, #41D8DD 100%);background: linear-gradient(to right, #5583EE 0%, #41D8DD 100%);filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#5583EE', endColorstr='#41D8DD',GradientType=1 );*/
}
h1{
color:rgb(225,223,220);
+6 -3
View File
@@ -1,7 +1,7 @@
/*-- ========================================= --
0.0 CSS IMPORT
/*-- ========================================= --*/
@import url("bootstrap.min.css");
@import url("/static/css/bootstrap.min.css");
@import url("font-awesome.min.css");
@import url("animate.min.css");
@import url("owl.carousel.css");
@@ -371,6 +371,8 @@ a.link-1.active::before
color:#262626;
background:#4ebd87;
width: 200px;
border-radius: 25px;
margin-top: 5px;
}
.button-green::before{
background:#4ebd87;
@@ -1736,7 +1738,7 @@ section .half-overlay.is-visible{
top:100%;
}
.about-section .bg-container-static{
background:url(../img/background/sample2.jpg) no-repeat;
/*background:url(../img/background/sample2.jpg) no-repeat;*/
background-size:cover;
background-position:50% 50%;
}
@@ -1860,7 +1862,7 @@ section .half-overlay.is-visible{
}
.works-section .bg-container-static{
background:url(../img/background/sample3.jpg) no-repeat;
/*background:url(../img/background/sample3.jpg) no-repeat;*/
background-size:cover;
background-position:50% 50%;
}
@@ -2163,6 +2165,7 @@ canvas#bg-canvas{
left:0px;
top:0px;
z-index:1;
background: rgba(38,38,38,0.7);
}
-1
View File
@@ -1 +0,0 @@
临时图片路径
@@ -0,0 +1,211 @@
body{ background-color:#fcfcfc;}
.grid {
position: relative;
margin: 0 auto;
}
.js .grid::after {
content: '';
position: absolute;
width: 100%;
height: 100%;
top: 0;
left: 0;
pointer-events: none;
background-size: 60px auto;
-webkit-transition: opacity 0.3s;
transition: opacity 0.3s;
}
.js .grid--loaded::after {
opacity: 0;
}
.grid__item {
width: 270px;
padding: 10px;
}
.grid__item--current {
opacity: 0 !important;
}
.img-wrap {
display: block;
}
.img-wrap:focus,
.img-wrap:hover {
outline: none;
}
.img-wrap img {
display: block;
max-width: 100%;
}
.preview {
position: fixed;
z-index: 1000;
top: 0;
left: 0;
display: -webkit-flex;
display: -ms-flex;
display: flex;
-ms-flex-pack: center;
-webkit-justify-content: center;
justify-content: center;
-ms-flex-line-pack: center;
-webkit-align-content: center;
align-content: center;
-ms-flex-align: center;
-webkit-align-items: center;
align-items: center;
width: 100%;
height: 100%;
pointer-events: none;
}
.preview--open {
pointer-events: auto;
}
/* circle overlay (generated SVG) */
.overlay {
position: absolute;
top: 0;
left: 0;
pointer-events: none;
}
.overlay circle {
-webkit-transition: fill-opacity 0.3s, -webkit-transform 0s 0.3s;
transition: fill-opacity 0.3s, transform 0s 0.3s;
-webkit-transition-timing-function: ease-out;
transition-timing-function: ease-out;
-webkit-transform: scale3d(0, 0, 1);
transform: scale3d(0, 0, 1);
fill: #1f1d1d;
fill-opacity: 0;
}
.preview--open .overlay circle {
-webkit-transition: -webkit-transform 0.4s;
transition: transform 0.4s;
-webkit-transform: scale3d(1, 1, 1);
transform: scale3d(1, 1, 1);
fill-opacity: 1;
}
.clone {
position: fixed;
z-index: 110;
-webkit-transition: -webkit-transform 0.6s cubic-bezier(0.5, 1, 0.2, 1);
transition: transform 0.6s cubic-bezier(0.5, 1, 0.2, 1);
-webkit-backface-visibility: hidden;
}
.original {
position: relative;
z-index: 120;
display: block;
object-fit: contain;
-webkit-transition: opacity 0.2s;
transition: opacity 0.2s;
-webkit-backface-visibility: hidden;
}
.preview--open .animate {
/* open */
-webkit-transition: -webkit-transform 0.6s, opacity 0.2s;
transition: transform 0.6s, opacity 0.2s;
}
.animate {
/* close */
-webkit-transition: -webkit-transform 0.3s, opacity 0.2s;
transition: transform 0.3s, opacity 0.2s;
}
.description {
color: #fff;
}
.js .description--grid {
display: none;
}
.description--preview {
position: fixed;
z-index: 140;
bottom: 0;
left: 0;
width: 100%;
padding: 2em 1em;
text-align: center;
opacity: 0;
background: linear-gradient(180deg, transparent, #1f1d1d);
-webkit-transition: opacity 0.3s, -webkit-transform 0.3s;
transition: opacity 0.3s, transform 0.3s;
-webkit-transform: translate3d(0, 100%, 0);
transform: translate3d(0, 100%, 0);
}
.preview--open .description--preview {
opacity: 1;
-webkit-transition-delay: 0.2s;
transition-delay: 0.2s;
-webkit-transform: translate3d(0, 0, 0);
transform: translate3d(0, 0, 0);
}
/* Close button */
.action {
font-size: 1.5em;
margin: 0;
padding: 0;
cursor: pointer;
vertical-align: top;
color: #6bd68a;
border: none;
background: none;
}
.action:hover,
.action:focus {
color: #6bd68a;
outline: none;
}
.action--close {
position: fixed;
z-index: 150;
top: 0;
right: 0;
padding: 1em;
opacity: 0;
-webkit-transition: opacity 0.3s, -webkit-transform 0.3s;
transition: opacity 0.3s, transform 0.3s;
-webkit-transform: scale3d(0.6, 0.6, 1);
transform: scale3d(0.6, 0.6, 1);
}
.preview--image-loaded .action--close {
opacity: 1;
-webkit-transform: scale3d(1, 1, 1);
transform: scale3d(1, 1, 1);
}
.text-hidden {
position: absolute;
display: block;
overflow: hidden;
width: 0;
height: 0;
color: transparent;
}
@@ -0,0 +1,164 @@
#verification{
margin-top: 100px;
}
.container{
color: #555;
}
.ghost {
position: relative;
animation: ghostUpdown 1s infinite alternate;
-webkit-animation: ghostUpdown 1s infinite alternate;
}
.sign-content.popup-in-content{
background: #fff;
border-radius: 5px;
padding: 60px 0 100px;
}
.popup-in-txt {
max-width: 500px;
margin: 0 auto;
}
.btn.signin_btn, .btn.signin_btn:focus {
width: 90%;
padding: 0;
height: 50px;
background: #5a84fd;
color: #fff;
font-size: 14px;
text-transform: uppercase;
border-radius: 3px;
box-shadow: 0 5px 30px rgba(0,66,255,.3);
margin-top: 23px;
margin: 15px;
}
.container ul{
padding: 0;
margin: 0 auto;
list-style: none;
}
.container ul li {
list-style: none;
}
/*=============Style css=========*/
.tlinks{text-indent:-9999px;height:0;line-height:0;font-size:0;overflow:hidden;}
/*-------------------------------------
2. Kit-name-head
--------------------------------------*/
.kit-name-head{
display: none;
height: 120px;
}
.kit-name-txt{
/*padding: 75px 0 71px;*/
padding: 33px 0 71px;
text-align: center;
}
.kit-name-head h2 {
font-size: 33px;
font-weight: 600;
color: #fff;
margin-bottom: 8px;/*18*/
}
.kit-name-head h2::first-letter {
text-transform: lowercase;
}
.kit-name-head h3{
font-size: 16px;
font-weight: 500;
color: #fff;
}
/*-------------------------------------
3. Form-demo
--------------------------------------*/
.single-form-demo-set {
text-align: center;
padding: 60px 0;
}
.single-form-img-content { margin-top: 60px;}
/*.form-img*/
.form-img {
position: relative;
box-shadow:0px 5px 30px 5px rgba(154,154,154,.3);
-webkit-transition: .5s;
-moz-transition:.5s;
-ms-transition:.5s;
-o-transition:.5s;
transition: .5s;
}
.form-img-hover{
display: flex;
justify-content: center;
align-items: center;
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background:transparent;
-webkit-transform: scale(0);
-moz-transform:scale(0);
-ms-transform:scale(0);
-o-transform:scale(0);
transform: scale(0);
}
.form-img:hover .form-img-hover{
-webkit-transform: scale(1);
-moz-transform:scale(1);
-ms-transform:scale(1);
-o-transform:scale(1);
transform: scale(1);
-webkit-transition: .5s;
-moz-transition:.5s;
-ms-transition:.5s;
-o-transition:.5s;
transition: .5s;
}
.form-img:hover {
box-shadow:0px 5px 30px 5px rgba(154,154,154,.7);
}
/*.form-img*/
/*===============================
Scroll Top
===============================*/
#scroll-Top .return-to-top {
position: fixed;
right: 30px;
bottom: 30px;
display: none;
width: 40px;
line-height: 40px;
height: 40px;
text-align: center;
font-size: 30px;
cursor: pointer;
color: #fff;
background:#5a84fd;
border:1px solid #5a84fd;
border-radius:5px;
-webkit-transition: .5s;
-moz-transition:.5s;
-ms-transition:.5s;
-o-transition:.5s;
transition: .5s;
z-index: 2;
}
#scroll-Top .return-to-top:hover {
background:transparent;
color: #26d9b3;
border:1px solid #26d9b3;
border-radius:50%;
}
/*========================Thank you=================
@@ -0,0 +1,85 @@
/*!
* classie v1.0.1
* class helper functions
* from bonzo https://github.com/ded/bonzo
* MIT license
*
* classie.has( elem, 'my-class' ) -> true/false
* classie.add( elem, 'my-new-class' )
* classie.remove( elem, 'my-unwanted-class' )
* classie.toggle( elem, 'my-class' )
*/
/*jshint browser: true, strict: true, undef: true, unused: true */
/*global define: false, module: false */
( function( window ) {
'use strict';
// class helper functions from bonzo https://github.com/ded/bonzo
function classReg( className ) {
return new RegExp("(^|\\s+)" + className + "(\\s+|$)");
}
// classList support for class management
// altho to be fair, the api sucks because it won't accept multiple classes at once
var hasClass, addClass, removeClass;
if ( 'classList' in document.documentElement ) {
hasClass = function( elem, c ) {
return elem.classList.contains( c );
};
addClass = function( elem, c ) {
elem.classList.add( c );
};
removeClass = function( elem, c ) {
elem.classList.remove( c );
};
}
else {
hasClass = function( elem, c ) {
return classReg( c ).test( elem.className );
};
addClass = function( elem, c ) {
if ( !hasClass( elem, c ) ) {
elem.className = elem.className + ' ' + c;
}
};
removeClass = function( elem, c ) {
elem.className = elem.className.replace( classReg( c ), ' ' );
};
}
function toggleClass( elem, c ) {
var fn = hasClass( elem, c ) ? removeClass : addClass;
fn( elem, c );
}
var classie = {
// full names
hasClass: hasClass,
addClass: addClass,
removeClass: removeClass,
toggleClass: toggleClass,
// short names
has: hasClass,
add: addClass,
remove: removeClass,
toggle: toggleClass
};
// transport
if ( typeof define === 'function' && define.amd ) {
// AMD
define( classie );
} else if ( typeof exports === 'object' ) {
// CommonJS
module.exports = classie;
} else {
// browser global
window.classie = classie;
}
})( window );
+1
View File
@@ -0,0 +1 @@
(function(k,m){var g="3.7.0";var d=k.html5||{};var h=/^<|^(?:button|map|select|textarea|object|iframe|option|optgroup)$/i;var c=/^(?:a|b|code|div|fieldset|h1|h2|h3|h4|h5|h6|i|label|li|ol|p|q|span|strong|style|table|tbody|td|th|tr|ul)$/i;var q;var i="_html5shiv";var a=0;var o={};var e;(function(){try{var t=m.createElement("a");t.innerHTML="<xyz></xyz>";q=("hidden" in t);e=t.childNodes.length==1||(function(){(m.createElement)("a");var v=m.createDocumentFragment();return(typeof v.cloneNode=="undefined"||typeof v.createDocumentFragment=="undefined"||typeof v.createElement=="undefined")}())}catch(u){q=true;e=true}}());function f(t,v){var w=t.createElement("p"),u=t.getElementsByTagName("head")[0]||t.documentElement;w.innerHTML="x<style>"+v+"</style>";return u.insertBefore(w.lastChild,u.firstChild)}function l(){var t=j.elements;return typeof t=="string"?t.split(" "):t}function p(t){var u=o[t[i]];if(!u){u={};a++;t[i]=a;o[a]=u}return u}function n(w,t,v){if(!t){t=m}if(e){return t.createElement(w)}if(!v){v=p(t)}var u;if(v.cache[w]){u=v.cache[w].cloneNode()}else{if(c.test(w)){u=(v.cache[w]=v.createElem(w)).cloneNode()}else{u=v.createElem(w)}}return u.canHaveChildren&&!h.test(w)?v.frag.appendChild(u):u}function r(v,x){if(!v){v=m}if(e){return v.createDocumentFragment()}x=x||p(v);var y=x.frag.cloneNode(),w=0,u=l(),t=u.length;for(;w<t;w++){y.createElement(u[w])}return y}function s(t,u){if(!u.cache){u.cache={};u.createElem=t.createElement;u.createFrag=t.createDocumentFragment;u.frag=u.createFrag()}t.createElement=function(v){if(!j.shivMethods){return u.createElem(v)}return n(v,t,u)};t.createDocumentFragment=Function("h,f","return function(){var n=f.cloneNode(),c=n.createElement;h.shivMethods&&("+l().join().replace(/[\w\-]+/g,function(v){u.createElem(v);u.frag.createElement(v);return'c("'+v+'")'})+");return n}")(j,u.frag)}function b(t){if(!t){t=m}var u=p(t);if(j.shivCSS&&!q&&!u.hasCSS){u.hasCSS=!!f(t,"article,aside,dialog,figcaption,figure,footer,header,hgroup,main,nav,section{display:block}mark{background:#FF0;color:#000}template{display:none}")}if(!e){s(t,u)}return t}var j={elements:d.elements||"abbr article aside audio bdi canvas data datalist details dialog figcaption figure footer header hgroup main mark meter nav output progress section summary template time video",version:g,shivCSS:(d.shivCSS!==false),supportsUnknownElements:e,shivMethods:(d.shivMethods!==false),type:"default",shivDocument:b,createElement:n,createDocumentFragment:r};k.html5=j;b(m)}(this,document));
File diff suppressed because one or more lines are too long
@@ -0,0 +1,364 @@
/**
* cbpGridGallery.js v1.0.0
* http://www.codrops.com
*
* Licensed under the MIT license.
* http://www.opensource.org/licenses/mit-license.php
*
* Copyright 2014, Codrops
* http://www.codrops.com
*/
;( function( window ) {
'use strict';
var docElem = window.document.documentElement,
transEndEventNames = {
'WebkitTransition': 'webkitTransitionEnd',
'MozTransition': 'transitionend',
'OTransition': 'oTransitionEnd',
'msTransition': 'MSTransitionEnd',
'transition': 'transitionend'
},
transEndEventName = transEndEventNames[ Modernizr.prefixed( 'transition' ) ],
support = {
transitions : Modernizr.csstransitions,
support3d : Modernizr.csstransforms3d
};
function setTransform( el, transformStr ) {
el.style.WebkitTransform = transformStr;
el.style.msTransform = transformStr;
el.style.transform = transformStr;
}
// from http://responsejs.com/labs/dimensions/
function getViewportW() {
var client = docElem['clientWidth'],
inner = window['innerWidth'];
if( client < inner )
return inner;
else
return client;
}
function extend( a, b ) {
for( var key in b ) {
if( b.hasOwnProperty( key ) ) {
a[key] = b[key];
}
}
return a;
}
function CBPGridGallery( el, options ) {
this.el = el;
this.options = extend( {}, this.options );
extend( this.options, options );
this._init();
}
CBPGridGallery.prototype.options = {
};
CBPGridGallery.prototype._init = function() {
// main grid
this.grid = this.el.querySelector( 'section.grid-wrap > ul.grid' );
// main grid items
this.gridItems = [].slice.call( this.grid.querySelectorAll( 'li:not(.grid-sizer)' ) );
// items total
this.itemsCount = this.gridItems.length;
// slideshow grid
this.slideshow = this.el.querySelector( 'section.slideshow > ul' );
// slideshow grid items
this.slideshowItems = [].slice.call( this.slideshow.children );
// index of current slideshow item
this.current = -1;
// slideshow control buttons
this.ctrlPrev = this.el.querySelector( 'section.slideshow > nav > span.nav-prev' );
this.ctrlNext = this.el.querySelector( 'section.slideshow > nav > span.nav-next' );
this.ctrlClose = this.el.querySelector( 'section.slideshow > nav > span.nav-close' );
// init masonry grid
this._initMasonry();
// init events
this._initEvents();
};
CBPGridGallery.prototype._initMasonry = function() {
var grid = this.grid;
imagesLoaded( grid, function() {
new Masonry( grid, {
itemSelector: 'li',
columnWidth: grid.querySelector( '.grid-sizer' )
});
});
};
CBPGridGallery.prototype._initEvents = function() {
var self = this;
// open the slideshow when clicking on the main grid items
this.gridItems.forEach( function( item, idx ) {
item.addEventListener( 'click', function() {
self._openSlideshow( idx );
} );
} );
// slideshow controls
this.ctrlPrev.addEventListener( 'click', function() { self._navigate( 'prev' ); } );
this.ctrlNext.addEventListener( 'click', function() { self._navigate( 'next' ); } );
this.ctrlClose.addEventListener( 'click', function() { self._closeSlideshow(); } );
// window resize
window.addEventListener( 'resize', function() { self._resizeHandler(); } );
// keyboard navigation events
document.addEventListener( 'keydown', function( ev ) {
if ( self.isSlideshowVisible ) {
var keyCode = ev.keyCode || ev.which;
switch (keyCode) {
case 37:
self._navigate( 'prev' );
break;
case 39:
self._navigate( 'next' );
break;
case 27:
self._closeSlideshow();
break;
}
}
} );
// trick to prevent scrolling when slideshow is visible
window.addEventListener( 'scroll', function() {
if ( self.isSlideshowVisible ) {
window.scrollTo( self.scrollPosition ? self.scrollPosition.x : 0, self.scrollPosition ? self.scrollPosition.y : 0 );
}
else {
self.scrollPosition = { x : window.pageXOffset || docElem.scrollLeft, y : window.pageYOffset || docElem.scrollTop };
}
});
};
CBPGridGallery.prototype._openSlideshow = function( pos ) {
this.isSlideshowVisible = true;
this.current = pos;
classie.addClass( this.el, 'slideshow-open' );
/* position slideshow items */
// set viewport items (current, next and previous)
this._setViewportItems();
// add class "current" and "show" to currentItem
classie.addClass( this.currentItem, 'current' );
classie.addClass( this.currentItem, 'show' );
// add class show to next and previous items
// position previous item on the left side and the next item on the right side
if( this.prevItem ) {
classie.addClass( this.prevItem, 'show' );
var translateVal = Number( -1 * ( getViewportW() / 2 + this.prevItem.offsetWidth / 2 ) );
setTransform( this.prevItem, support.support3d ? 'translate3d(' + translateVal + 'px, 0, -150px)' : 'translate(' + translateVal + 'px)' );
}
if( this.nextItem ) {
classie.addClass( this.nextItem, 'show' );
var translateVal = Number( getViewportW() / 2 + this.nextItem.offsetWidth / 2 );
setTransform( this.nextItem, support.support3d ? 'translate3d(' + translateVal + 'px, 0, -150px)' : 'translate(' + translateVal + 'px)' );
}
};
CBPGridGallery.prototype._navigate = function( dir ) {
if( this.isAnimating ) return;
if( dir === 'next' && this.current === this.itemsCount - 1 || dir === 'prev' && this.current === 0 ) {
this._closeSlideshow();
return;
}
this.isAnimating = true;
// reset viewport items
this._setViewportItems();
var self = this,
itemWidth = this.currentItem.offsetWidth,
// positions for the centered/current item, both the side items and the incoming ones
transformLeftStr = support.support3d ? 'translate3d(-' + Number( getViewportW() / 2 + itemWidth / 2 ) + 'px, 0, -150px)' : 'translate(-' + Number( getViewportW() / 2 + itemWidth / 2 ) + 'px)',
transformRightStr = support.support3d ? 'translate3d(' + Number( getViewportW() / 2 + itemWidth / 2 ) + 'px, 0, -150px)' : 'translate(' + Number( getViewportW() / 2 + itemWidth / 2 ) + 'px)',
transformCenterStr = '', transformOutStr, transformIncomingStr,
// incoming item
incomingItem;
if( dir === 'next' ) {
transformOutStr = support.support3d ? 'translate3d( -' + Number( (getViewportW() * 2) / 2 + itemWidth / 2 ) + 'px, 0, -150px )' : 'translate(-' + Number( (getViewportW() * 2) / 2 + itemWidth / 2 ) + 'px)';
transformIncomingStr = support.support3d ? 'translate3d( ' + Number( (getViewportW() * 2) / 2 + itemWidth / 2 ) + 'px, 0, -150px )' : 'translate(' + Number( (getViewportW() * 2) / 2 + itemWidth / 2 ) + 'px)';
}
else {
transformOutStr = support.support3d ? 'translate3d( ' + Number( (getViewportW() * 2) / 2 + itemWidth / 2 ) + 'px, 0, -150px )' : 'translate(' + Number( (getViewportW() * 2) / 2 + itemWidth / 2 ) + 'px)';
transformIncomingStr = support.support3d ? 'translate3d( -' + Number( (getViewportW() * 2) / 2 + itemWidth / 2 ) + 'px, 0, -150px )' : 'translate(-' + Number( (getViewportW() * 2) / 2 + itemWidth / 2 ) + 'px)';
}
// remove class animatable from the slideshow grid (if it has already)
classie.removeClass( self.slideshow, 'animatable' );
if( dir === 'next' && this.current < this.itemsCount - 2 || dir === 'prev' && this.current > 1 ) {
// we have an incoming item!
incomingItem = this.slideshowItems[ dir === 'next' ? this.current + 2 : this.current - 2 ];
setTransform( incomingItem, transformIncomingStr );
classie.addClass( incomingItem, 'show' );
}
var slide = function() {
// add class animatable to the slideshow grid
classie.addClass( self.slideshow, 'animatable' );
// overlays:
classie.removeClass( self.currentItem, 'current' );
var nextCurrent = dir === 'next' ? self.nextItem : self.prevItem;
classie.addClass( nextCurrent, 'current' );
setTransform( self.currentItem, dir === 'next' ? transformLeftStr : transformRightStr );
if( self.nextItem ) {
setTransform( self.nextItem, dir === 'next' ? transformCenterStr : transformOutStr );
}
if( self.prevItem ) {
setTransform( self.prevItem, dir === 'next' ? transformOutStr : transformCenterStr );
}
if( incomingItem ) {
setTransform( incomingItem, dir === 'next' ? transformRightStr : transformLeftStr );
}
var onEndTransitionFn = function( ev ) {
if( support.transitions ) {
if( ev.propertyName.indexOf( 'transform' ) === -1 ) return false;
this.removeEventListener( transEndEventName, onEndTransitionFn );
}
if( self.prevItem && dir === 'next' ) {
classie.removeClass( self.prevItem, 'show' );
}
else if( self.nextItem && dir === 'prev' ) {
classie.removeClass( self.nextItem, 'show' );
}
if( dir === 'next' ) {
self.prevItem = self.currentItem;
self.currentItem = self.nextItem;
if( incomingItem ) {
self.nextItem = incomingItem;
}
}
else {
self.nextItem = self.currentItem;
self.currentItem = self.prevItem;
if( incomingItem ) {
self.prevItem = incomingItem;
}
}
self.current = dir === 'next' ? self.current + 1 : self.current - 1;
self.isAnimating = false;
};
if( support.transitions ) {
self.currentItem.addEventListener( transEndEventName, onEndTransitionFn );
}
else {
onEndTransitionFn();
}
};
setTimeout( slide, 25 );
}
CBPGridGallery.prototype._closeSlideshow = function( pos ) {
// remove class slideshow-open from the grid gallery elem
classie.removeClass( this.el, 'slideshow-open' );
// remove class animatable from the slideshow grid
classie.removeClass( this.slideshow, 'animatable' );
var self = this,
onEndTransitionFn = function( ev ) {
if( support.transitions ) {
if( ev.target.tagName.toLowerCase() !== 'ul' ) return;
this.removeEventListener( transEndEventName, onEndTransitionFn );
}
// remove classes show and current from the slideshow items
classie.removeClass( self.currentItem, 'current' );
classie.removeClass( self.currentItem, 'show' );
if( self.prevItem ) {
classie.removeClass( self.prevItem, 'show' );
}
if( self.nextItem ) {
classie.removeClass( self.nextItem, 'show' );
}
// also reset any transforms for all the items
self.slideshowItems.forEach( function( item ) { setTransform( item, '' ); } );
self.isSlideshowVisible = false;
};
if( support.transitions ) {
this.el.addEventListener( transEndEventName, onEndTransitionFn );
}
else {
onEndTransitionFn();
}
};
CBPGridGallery.prototype._setViewportItems = function() {
this.currentItem = null;
this.prevItem = null;
this.nextItem = null;
if( this.current > 0 ) {
this.prevItem = this.slideshowItems[ this.current - 1 ];
}
if( this.current < this.itemsCount - 1 ) {
this.nextItem = this.slideshowItems[ this.current + 1 ];
}
this.currentItem = this.slideshowItems[ this.current ];
}
// taken from https://github.com/desandro/vanilla-masonry/blob/master/masonry.js by David DeSandro
// original debounce by John Hann
// http://unscriptable.com/index.php/2009/03/20/debouncing-javascript-methods/
CBPGridGallery.prototype._resizeHandler = function() {
var self = this;
function delayed() {
self._resize();
self._resizeTimeout = null;
}
if ( this._resizeTimeout ) {
clearTimeout( this._resizeTimeout );
}
this._resizeTimeout = setTimeout( delayed, 50 );
}
CBPGridGallery.prototype._resize = function() {
if ( this.isSlideshowVisible ) {
// update width value
if( this.prevItem ) {
var translateVal = Number( -1 * ( getViewportW() / 2 + this.prevItem.offsetWidth / 2 ) );
setTransform( this.prevItem, support.support3d ? 'translate3d(' + translateVal + 'px, 0, -150px)' : 'translate(' + translateVal + 'px)' );
}
if( this.nextItem ) {
var translateVal = Number( getViewportW() / 2 + this.nextItem.offsetWidth / 2 );
setTransform( this.nextItem, support.support3d ? 'translate3d(' + translateVal + 'px, 0, -150px)' : 'translate(' + translateVal + 'px)' );
}
}
}
// add to global namespace
window.CBPGridGallery = CBPGridGallery;
})( window );
@@ -0,0 +1,80 @@
/*!
* classie - class helper functions
* from bonzo https://github.com/ded/bonzo
*
* classie.has( elem, 'my-class' ) -> true/false
* classie.add( elem, 'my-new-class' )
* classie.remove( elem, 'my-unwanted-class' )
* classie.toggle( elem, 'my-class' )
*/
/*jshint browser: true, strict: true, undef: true */
/*global define: false */
( function( window ) {
'use strict';
// class helper functions from bonzo https://github.com/ded/bonzo
function classReg( className ) {
return new RegExp("(^|\\s+)" + className + "(\\s+|$)");
}
// classList support for class management
// altho to be fair, the api sucks because it won't accept multiple classes at once
var hasClass, addClass, removeClass;
if ( 'classList' in document.documentElement ) {
hasClass = function( elem, c ) {
return elem.classList.contains( c );
};
addClass = function( elem, c ) {
elem.classList.add( c );
};
removeClass = function( elem, c ) {
elem.classList.remove( c );
};
}
else {
hasClass = function( elem, c ) {
return classReg( c ).test( elem.className );
};
addClass = function( elem, c ) {
if ( !hasClass( elem, c ) ) {
elem.className = elem.className + ' ' + c;
}
};
removeClass = function( elem, c ) {
elem.className = elem.className.replace( classReg( c ), ' ' );
};
}
function toggleClass( elem, c ) {
var fn = hasClass( elem, c ) ? removeClass : addClass;
fn( elem, c );
}
var classie = {
// full names
hasClass: hasClass,
addClass: addClass,
removeClass: removeClass,
toggleClass: toggleClass,
// short names
has: hasClass,
add: addClass,
remove: removeClass,
toggle: toggleClass
};
// transport
if ( typeof define === 'function' && define.amd ) {
// AMD
define( classie );
} else {
// browser global
window.classie = classie;
}
})( window );
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -0,0 +1,347 @@
;(function(window) {
'use strict';
var support = { transitions: Modernizr.csstransitions },
// transition end event name
transEndEventNames = { 'WebkitTransition': 'webkitTransitionEnd', 'MozTransition': 'transitionend', 'OTransition': 'oTransitionEnd', 'msTransition': 'MSTransitionEnd', 'transition': 'transitionend' },
transEndEventName = transEndEventNames[ Modernizr.prefixed( 'transition' ) ],
onEndTransition = function( el, callback ) {
var onEndCallbackFn = function( ev ) {
if( support.transitions ) {
if( ev.target != this ) return;
this.removeEventListener( transEndEventName, onEndCallbackFn );
}
if( callback && typeof callback === 'function' ) { callback.call(this); }
};
if( support.transitions ) {
el.addEventListener( transEndEventName, onEndCallbackFn );
}
else {
onEndCallbackFn();
}
};
/**
* some helper functions
*/
function throttle(fn, delay) {
var allowSample = true;
return function(e) {
if (allowSample) {
allowSample = false;
setTimeout(function() { allowSample = true; }, delay);
fn(e);
}
};
}
function nextSibling(el) {
var nextSibling = el.nextSibling;
while(nextSibling && nextSibling.nodeType != 1) {
nextSibling = nextSibling.nextSibling
}
return nextSibling;
}
function extend( a, b ) {
for( var key in b ) {
if( b.hasOwnProperty( key ) ) {
a[key] = b[key];
}
}
return a;
}
/**
* GridFx obj
*/
function GridFx(el, options) {
this.gridEl = el;
this.options = extend( {}, this.options );
extend( this.options, options );
this.items = [].slice.call(this.gridEl.querySelectorAll('.grid__item'));
this.previewEl = nextSibling(this.gridEl);
this.isExpanded = false;
this.isAnimating = false;
this.closeCtrl = this.previewEl.querySelector('button.action--close');
this.previewDescriptionEl = this.previewEl.querySelector('.description--preview');
this._init();
}
/**
* options
*/
GridFx.prototype.options = {
pagemargin : 0,
// x and y can have values from 0 to 1 (percentage). If negative then it means the alignment is left and/or top rather than right and/or bottom
// so, as an example, if we want our large image to be positioned vertically on 25% of the screen and centered horizontally the values would be x:1,y:-0.25
imgPosition : { x : 1, y : 1 },
onInit : function(instance) { return false; },
onResize : function(instance) { return false; },
onOpenItem : function(instance, item) { return false; },
onCloseItem : function(instance, item) { return false; },
onExpand : function() { return false; }
}
GridFx.prototype._init = function() {
// callback
this.options.onInit(this);
var self = this;
// init masonry after all images are loaded
imagesLoaded( this.gridEl, function() {
// initialize masonry
new Masonry(self.gridEl, {
itemSelector: '.grid__item',
isFitWidth : true
});
// show grid after all images (thumbs) are loaded
classie.add(self.gridEl, 'grid--loaded');
// init/bind events
self._initEvents();
// create the large image and append it to the DOM
self._setOriginal();
// create the clone image and append it to the DOM
self._setClone();
});
};
/**
* initialize/bind events
*/
GridFx.prototype._initEvents = function () {
var self = this,
clickEvent = (document.ontouchstart!==null ? 'click' : 'touchstart');
this.items.forEach(function(item) {
var touchend = function(ev) {
ev.preventDefault();
self._openItem(ev, item);
item.removeEventListener('touchend', touchend);
},
touchmove = function(ev) {
item.removeEventListener('touchend', touchend);
},
manageTouch = function() {
item.addEventListener('touchend', touchend);
item.addEventListener('touchmove', touchmove);
};
item.addEventListener(clickEvent, function(ev) {
if(clickEvent === 'click') {
ev.preventDefault();
self._openItem(ev, item);
}
else {
manageTouch();
}
});
});
// close expanded image
this.closeCtrl.addEventListener('click', function() {
self._closeItem();
});
window.addEventListener('resize', throttle(function(ev) {
// callback
self.options.onResize(self);
}, 10));
}
/**
* open a grid item
*/
GridFx.prototype._openItem = function(ev, item) {
if( this.isAnimating || this.isExpanded ) return;
this.isAnimating = true;
this.isExpanded = true;
// item's image
var gridImg = item.querySelector('img'),
gridImgOffset = gridImg.getBoundingClientRect();
// index of current item
this.current = this.items.indexOf(item);
// set the src of the original image element (large image)
this._setOriginal(item.querySelector('a').getAttribute('href'));
// callback
this.options.onOpenItem(this, item);
// set the clone image
this._setClone(gridImg.src, {
width : gridImg.offsetWidth,
height : gridImg.offsetHeight,
left : gridImgOffset.left,
top : gridImgOffset.top
});
// hide original grid item
classie.add(item, 'grid__item--current');
// calculate the transform value for the clone to animate to the full image view
var win = this._getWinSize(),
originalSizeArr = item.getAttribute('data-size').split('x'),
originalSize = {width: originalSizeArr[0], height: originalSizeArr[1]},
dx = ((this.options.imgPosition.x > 0 ? 1-Math.abs(this.options.imgPosition.x) : Math.abs(this.options.imgPosition.x)) * win.width + this.options.imgPosition.x * win.width/2) - gridImgOffset.left - 0.5 * gridImg.offsetWidth,
dy = ((this.options.imgPosition.y > 0 ? 1-Math.abs(this.options.imgPosition.y) : Math.abs(this.options.imgPosition.y)) * win.height + this.options.imgPosition.y * win.height/2) - gridImgOffset.top - 0.5 * gridImg.offsetHeight,
z = Math.min( Math.min(win.width*Math.abs(this.options.imgPosition.x) - this.options.pagemargin, originalSize.width - this.options.pagemargin)/gridImg.offsetWidth, Math.min(win.height*Math.abs(this.options.imgPosition.y) - this.options.pagemargin, originalSize.height - this.options.pagemargin)/gridImg.offsetHeight );
// apply transform to the clone
this.cloneImg.style.WebkitTransform = 'translate3d(' + dx + 'px, ' + dy + 'px, 0) scale3d(' + z + ', ' + z + ', 1)';
this.cloneImg.style.transform = 'translate3d(' + dx + 'px, ' + dy + 'px, 0) scale3d(' + z + ', ' + z + ', 1)';
// add the description if any
var descriptionEl = item.querySelector('.description');
if( descriptionEl ) {
this.previewDescriptionEl.innerHTML = descriptionEl.innerHTML;
}
var self = this;
setTimeout(function() {
// controls the elements inside the expanded view
classie.add(self.previewEl, 'preview--open');
// callback
self.options.onExpand();
}, 0);
// after the clone animates..
onEndTransition(this.cloneImg, function() {
// when the original/large image is loaded..
imagesLoaded(self.originalImg, function() {
// close button just gets shown after the large image gets loaded
classie.add(self.previewEl, 'preview--image-loaded');
// animate the opacity to 1
self.originalImg.style.opacity = 1;
// and once that's done..
onEndTransition(self.originalImg, function() {
// reset cloneImg
self.cloneImg.style.opacity = 0;
self.cloneImg.style.WebkitTransform = 'translate3d(0,0,0) scale3d(1,1,1)';
self.cloneImg.style.transform = 'translate3d(0,0,0) scale3d(1,1,1)';
self.isAnimating = false;
});
});
});
};
/**
* create/set the original/large image element
*/
GridFx.prototype._setOriginal = function(src) {
if( !src ) {
this.originalImg = document.createElement('img');
this.originalImg.className = 'original';
this.originalImg.style.opacity = 0;
this.originalImg.style.maxWidth = 'calc(' + parseInt(Math.abs(this.options.imgPosition.x)*100) + 'vw - ' + this.options.pagemargin + 'px)';
this.originalImg.style.maxHeight = 'calc(' + parseInt(Math.abs(this.options.imgPosition.y)*100) + 'vh - ' + this.options.pagemargin + 'px)';
// need it because of firefox
this.originalImg.style.WebkitTransform = 'translate3d(0,0,0) scale3d(1,1,1)';
this.originalImg.style.transform = 'translate3d(0,0,0) scale3d(1,1,1)';
src = '';
this.previewEl.appendChild(this.originalImg);
}
this.originalImg.setAttribute('src', src);
};
/**
* create/set the clone image element
*/
GridFx.prototype._setClone = function(src, settings) {
if( !src ) {
this.cloneImg = document.createElement('img');
this.cloneImg.className = 'clone';
src = '';
this.cloneImg.style.opacity = 0;
this.previewEl.appendChild(this.cloneImg);
}
else {
this.cloneImg.style.opacity = 1;
// set top/left/width/height of grid item's image to the clone
this.cloneImg.style.width = settings.width + 'px';
this.cloneImg.style.height = settings.height + 'px';
this.cloneImg.style.top = settings.top + 'px';
this.cloneImg.style.left = settings.left + 'px';
}
this.cloneImg.setAttribute('src', src);
};
/**
* closes the original/large image view
*/
GridFx.prototype._closeItem = function() {
if( !this.isExpanded || this.isAnimating ) return;
this.isExpanded = false;
this.isAnimating = true;
// the grid item's image and its offset
var gridItem = this.items[this.current],
gridImg = gridItem.querySelector('img'),
gridImgOffset = gridImg.getBoundingClientRect(),
self = this;
classie.remove(this.previewEl, 'preview--open');
classie.remove(this.previewEl, 'preview--image-loaded');
// callback
this.options.onCloseItem(this, gridItem);
// large image will animate back to the position of its grid's item
classie.add(this.originalImg, 'animate');
// set the transform to the original/large image
var win = this._getWinSize(),
dx = gridImgOffset.left + gridImg.offsetWidth/2 - ((this.options.imgPosition.x > 0 ? 1-Math.abs(this.options.imgPosition.x) : Math.abs(this.options.imgPosition.x)) * win.width + this.options.imgPosition.x * win.width/2),
dy = gridImgOffset.top + gridImg.offsetHeight/2 - ((this.options.imgPosition.y > 0 ? 1-Math.abs(this.options.imgPosition.y) : Math.abs(this.options.imgPosition.y)) * win.height + this.options.imgPosition.y * win.height/2),
z = gridImg.offsetWidth/this.originalImg.offsetWidth;
this.originalImg.style.WebkitTransform = 'translate3d(' + dx + 'px, ' + dy + 'px, 0) scale3d(' + z + ', ' + z + ', 1)';
this.originalImg.style.transform = 'translate3d(' + dx + 'px, ' + dy + 'px, 0) scale3d(' + z + ', ' + z + ', 1)';
// once that's done..
onEndTransition(this.originalImg, function() {
// clear description
self.previewDescriptionEl.innerHTML = '';
// show original grid item
classie.remove(gridItem, 'grid__item--current');
// fade out the original image
setTimeout(function() { self.originalImg.style.opacity = 0; }, 60);
// and after that
onEndTransition(self.originalImg, function() {
// reset original/large image
classie.remove(self.originalImg, 'animate');
self.originalImg.style.WebkitTransform = 'translate3d(0,0,0) scale3d(1,1,1)';
self.originalImg.style.transform = 'translate3d(0,0,0) scale3d(1,1,1)';
self.isAnimating = false;
});
});
};
/**
* gets the window sizes
*/
GridFx.prototype._getWinSize = function() {
return {
width: document.documentElement.clientWidth,
height: window.innerHeight
};
};
window.GridFx = GridFx;
})(window);
File diff suppressed because one or more lines are too long
@@ -0,0 +1,3 @@
/*! modernizr 3.1.0 (Custom Build) | MIT *
* http://modernizr.com/download/?-csstransitions-prefixed !*/
!function(e,n,t){function r(e,n){return typeof e===n}function o(){var e,n,t,o,s,i,a;for(var f in C){if(e=[],n=C[f],n.name&&(e.push(n.name.toLowerCase()),n.options&&n.options.aliases&&n.options.aliases.length))for(t=0;t<n.options.aliases.length;t++)e.push(n.options.aliases[t].toLowerCase());for(o=r(n.fn,"function")?n.fn():n.fn,s=0;s<e.length;s++)i=e[s],a=i.split("."),1===a.length?Modernizr[a[0]]=o:(!Modernizr[a[0]]||Modernizr[a[0]]instanceof Boolean||(Modernizr[a[0]]=new Boolean(Modernizr[a[0]])),Modernizr[a[0]][a[1]]=o),g.push((o?"":"no-")+a.join("-"))}}function s(e){var n=x.className,t=Modernizr._config.classPrefix||"";if(w&&(n=n.baseVal),Modernizr._config.enableJSClass){var r=new RegExp("(^|\\s)"+t+"no-js(\\s|$)");n=n.replace(r,"$1"+t+"js$2")}Modernizr._config.enableClasses&&(n+=" "+t+e.join(" "+t),w?x.className.baseVal=n:x.className=n)}function i(e){return e.replace(/([a-z])-([a-z])/g,function(e,n,t){return n+t.toUpperCase()}).replace(/^-/,"")}function a(e,n){return!!~(""+e).indexOf(n)}function f(){return"function"!=typeof n.createElement?n.createElement(arguments[0]):w?n.createElementNS.call(n,"http://www.w3.org/2000/svg",arguments[0]):n.createElement.apply(n,arguments)}function l(e,n){return function(){return e.apply(n,arguments)}}function u(e,n,t){var o;for(var s in e)if(e[s]in n)return t===!1?e[s]:(o=n[e[s]],r(o,"function")?l(o,t||n):o);return!1}function p(e){return e.replace(/([A-Z])/g,function(e,n){return"-"+n.toLowerCase()}).replace(/^ms-/,"-ms-")}function d(){var e=n.body;return e||(e=f(w?"svg":"body"),e.fake=!0),e}function c(e,t,r,o){var s,i,a,l,u="modernizr",p=f("div"),c=d();if(parseInt(r,10))for(;r--;)a=f("div"),a.id=o?o[r]:u+(r+1),p.appendChild(a);return s=f("style"),s.type="text/css",s.id="s"+u,(c.fake?c:p).appendChild(s),c.appendChild(p),s.styleSheet?s.styleSheet.cssText=e:s.appendChild(n.createTextNode(e)),p.id=u,c.fake&&(c.style.background="",c.style.overflow="hidden",l=x.style.overflow,x.style.overflow="hidden",x.appendChild(c)),i=t(p,e),c.fake?(c.parentNode.removeChild(c),x.style.overflow=l,x.offsetHeight):p.parentNode.removeChild(p),!!i}function m(n,r){var o=n.length;if("CSS"in e&&"supports"in e.CSS){for(;o--;)if(e.CSS.supports(p(n[o]),r))return!0;return!1}if("CSSSupportsRule"in e){for(var s=[];o--;)s.push("("+p(n[o])+":"+r+")");return s=s.join(" or "),c("@supports ("+s+") { #modernizr { position: absolute; } }",function(e){return"absolute"==getComputedStyle(e,null).position})}return t}function v(e,n,o,s){function l(){p&&(delete P.style,delete P.modElem)}if(s=r(s,"undefined")?!1:s,!r(o,"undefined")){var u=m(e,o);if(!r(u,"undefined"))return u}for(var p,d,c,v,h,y=["modernizr","tspan"];!P.style;)p=!0,P.modElem=f(y.shift()),P.style=P.modElem.style;for(c=e.length,d=0;c>d;d++)if(v=e[d],h=P.style[v],a(v,"-")&&(v=i(v)),P.style[v]!==t){if(s||r(o,"undefined"))return l(),"pfx"==n?v:!0;try{P.style[v]=o}catch(g){}if(P.style[v]!=h)return l(),"pfx"==n?v:!0}return l(),!1}function h(e,n,t,o,s){var i=e.charAt(0).toUpperCase()+e.slice(1),a=(e+" "+b.join(i+" ")+i).split(" ");return r(n,"string")||r(n,"undefined")?v(a,n,o,s):(a=(e+" "+z.join(i+" ")+i).split(" "),u(a,n,t))}function y(e,n,r){return h(e,t,t,n,r)}var g=[],C=[],_={_version:"3.1.0",_config:{classPrefix:"",enableClasses:!0,enableJSClass:!0,usePrefixes:!0},_q:[],on:function(e,n){var t=this;setTimeout(function(){n(t[e])},0)},addTest:function(e,n,t){C.push({name:e,fn:n,options:t})},addAsyncTest:function(e){C.push({name:null,fn:e})}},Modernizr=function(){};Modernizr.prototype=_,Modernizr=new Modernizr;var x=n.documentElement,w="svg"===x.nodeName.toLowerCase(),S="Moz O ms Webkit",b=_._config.usePrefixes?S.split(" "):[];_._cssomPrefixes=b;var E=function(n){var r,o=prefixes.length,s=e.CSSRule;if("undefined"==typeof s)return t;if(!n)return!1;if(n=n.replace(/^@/,""),r=n.replace(/-/g,"_").toUpperCase()+"_RULE",r in s)return"@"+n;for(var i=0;o>i;i++){var a=prefixes[i],f=a.toUpperCase()+"_"+r;if(f in s)return"@-"+a.toLowerCase()+"-"+n}return!1};_.atRule=E;var z=_._config.usePrefixes?S.toLowerCase().split(" "):[];_._domPrefixes=z;var N={elem:f("modernizr")};Modernizr._q.push(function(){delete N.elem});var P={style:N.elem.style};Modernizr._q.unshift(function(){delete P.style}),_.testAllProps=h;_.prefixed=function(e,n,t){return 0===e.indexOf("@")?E(e):(-1!=e.indexOf("-")&&(e=i(e)),n?h(e,n,t):h(e,"pfx"))};_.testAllProps=y,Modernizr.addTest("csstransitions",y("transition","all",!0)),o(),s(g),delete _.addTest,delete _.addAsyncTest;for(var T=0;T<Modernizr._q.length;T++)Modernizr._q[T]();e.Modernizr=Modernizr}(window,document);
Binary file not shown.

After

Width:  |  Height:  |  Size: 2.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

+1
View File
@@ -0,0 +1 @@
!function(t){"use strict";function e(e){return this.each(function(){var i=t(this),n=i.data("plugin.backgroundBlur"),o=t.extend({},r.DEFAULTS,i.data(),"object"==typeof e&&e);n||i.data("plugin.backgroundBlur",n=new r(this,o)),"fadeIn"===e?n.fadeIn():"fadeOut"===e?n.fadeOut():"string"==typeof e&&n.generateBlurredImage(e)})}var i=function(){for(var t,e=3,i=document.createElement("div"),n=i.getElementsByTagName("i");i.innerHTML="<!--[if gt IE "+ ++e+"]><i></i><![endif]-->",n[0];);return e>4?e:t}(),n=function(){return"_"+Math.random().toString(36).substr(2,9)},o={svgns:"http://www.w3.org/2000/svg",xlink:"http://www.w3.org/1999/xlink",createElement:function(t,e){var i=document.createElementNS(o.svgns,t);return e&&o.setAttr(i,e),i},setAttr:function(t,e){for(var i in e)"href"===i?t.setAttributeNS(o.xlink,i,e[i]):t.setAttribute(i,e[i]);return t}},r=function(e,i){this.internalID=n(),this.$element=t(e),this.$width=this.$element.width(),this.$height=this.$element.height(),this.element=e,this.options=t.extend({},r.DEFAULTS,i),this.$overlayEl=this.createOverlay(),this.$blurredImage={},this.useVelocity=this.detectVelocity(),this.attachListeners(),this.generateBlurredImage(this.options.imageURL)};r.VERSION="0.0.1",r.DEFAULTS={imageURL:"",blurAmount:10,imageClass:"",overlayClass:"",duration:!1,opacity:1},r.prototype.detectVelocity=function(){return!!window.jQuery.Velocity},r.prototype.attachListeners=function(){this.$element.on("ui.blur.loaded",t.proxy(this.fadeIn,this)),this.$element.on("ui.blur.unload",t.proxy(this.fadeOut,this))},r.prototype.fadeIn=function(){this.options.duration&&this.options.duration>0&&(this.useVelocity?this.$blurredImage.velocity({opacity:this.options.opacity},{duration:this.options.duration}):this.$blurredImage.animate({opacity:this.options.opacity},{duration:this.options.duration}))},r.prototype.fadeOut=function(){this.options.duration&&this.options.duration>0?this.useVelocity?this.$blurredImage.velocity({opacity:0},{duration:this.options.duration}):this.$blurredImage.animate({opacity:0},{duration:this.options.duration}):this.$blurredImage.css({opacity:0})},r.prototype.generateBlurredImage=function(t){var e=this.$blurredImage;this.internalID=n(),e.length>0&&(this.options.duration&&this.options.duration>0?this.useVelocity?e.first().velocity({opacity:0},{duration:this.options.duration,complete:function(){e.remove()}}):e.first().animate({opacity:0},{duration:this.options.duration,complete:function(){e.remove()}}):e.remove()),this.$blurredImage=i?this.createIMG(t,this.$width,this.$height):this.createSVG(t,this.$width,this.$height)},r.prototype.createOverlay=function(){return this.options.overlayClass&&""!==this.options.overlayClass?t("<div></div>").prependTo(this.$element).addClass(this.options.overlayClass):!1},r.prototype.createSVG=function(e,i,n){var r=this,s=o.createElement("svg",{xmlns:o.svgns,version:"1.1",width:i,height:n,id:"blurred"+this.internalID,"class":this.options.imageClass,viewBox:"0 0 "+i+" "+n,preserveAspectRatio:"none"}),a="blur"+this.internalID,u=o.createElement("filter",{id:a}),l=o.createElement("feGaussianBlur",{"in":"SourceGraphic",stdDeviation:this.options.blurAmount}),h=o.createElement("image",{x:0,y:0,width:i,height:n,externalResourcesRequired:"true",href:e,style:"filter:url(#"+a+")",preserveAspectRatio:"none"});h.addEventListener("load",function(){r.$element.trigger("ui.blur.loaded")},!0),h.addEventListener("SVGLoad",function(){r.$element.trigger("ui.blur.loaded")},!0),u.appendChild(l),s.appendChild(u),s.appendChild(h);var d=t(s);return r.options.duration&&r.options.duration>0&&(d.css({opacity:0}),window.setTimeout(function(){"0"===d.css("opacity")&&d.css({opacity:1})},this.options.duration+100)),this.element.insertBefore(s,this.element.firstChild),d},r.prototype.createIMG=function(t,e,i){var n=this,o=this.prependImage(t),r=2*this.options.blurAmount>100?100:2*this.options.blurAmount;return o.css({filter:"progid:DXImageTransform.Microsoft.Blur(pixelradius="+r+") ",top:2.5*-this.options.blurAmount,left:2.5*-this.options.blurAmount,width:e+2.5*this.options.blurAmount,height:i+2.5*this.options.blurAmount}).attr("id","blurred"+this.internalID),o.load(function(){n.$element.trigger("ui.blur.loaded")}),this.options.duration&&this.options.duration>0&&window.setTimeout(function(){"0"===o.css("opacity")&&o.css({opacity:1})},this.options.duration+100),o},r.prototype.prependImage=function(e){var i,n=t('<img src="'+e+'" />');return i=this.$overlayEl?n.insertBefore(this.$overlayEl).attr("id",this.internalID).addClass(this.options.imageClass):n.prependTo(this.$element).attr("id",this.internalID).addClass(this.options.imageClass)};var s=t.fn.backgroundBlur;t.fn.backgroundBlur=e,t.fn.backgroundBlur.Constructor=r,t.fn.backgroundBlur.noConflict=function(){return t.fn.backgroundBlur=s,this}}(jQuery);
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+367
View File
@@ -0,0 +1,367 @@
$(function () {
$.ajax({
type: "POST",
url: "/islogin",
dataType: "json",
success: function (data) {
if(data.lgoinret==1){
bodys(data.username);
}else{
}
}
});
});
function bodys(username) {
var h = '';//<li class="active"><a class="menu-link" data-section="home" data-nav-title="home" data-section-pos="0" data-section-posy="0">'+username+'<i class="fa fa-fw fa-user"></i></a></li>
var h1 = '<li><a class="menu-link" target="_blank" href="/admin/goadmin" id="usernames">控制台&nbsp;<i class="fa fa-fw fa-list"></i></a></li>';
var h2 = '<li><a class="menu-link" style="cursor: pointer;" onclick="exit()">退&nbsp;出&nbsp;<span class="glyphicon glyphicon-log-out"></span></a></li>';
$("#usersrc").html(h + h1 + h2);
}
function zhuce(mail, registerusername, registerpassword) {
if(zcverification){
//验证成功
$.ajax({
type: "POST",
url: "/user/register",
data: {email: mail, username: registerusername, password: registerpassword,zctmp:zctmp},
dataType: "json",
success: function (data) {
if (data.ret > 0) {
$("#zctishi").text('注册成功');
if (data.zctype == 1) {
layer.alert('注册成功,请前往邮箱激活你的账号,注意!激活邮件如果迟迟未收到,有可能在您的【垃圾箱】中。', {
skin: 'layui-layer-molv'
,closeBtn: 0
,anim: 1
,btn: ['确定']
,icon: 1
,yes:function(){
window.location.reload();
}
});
} else {
layer.alert('注册成功,快去登录体验吧。', {
skin: 'layui-layer-molv'
,closeBtn: 0
,anim: 1
,btn: ['确定']
,icon: 1
,yes:function(){
window.location.reload();
}
});
}
} else {
if (data.ret == -2) {
layer.alert('注册失败,用户名或邮箱重复且用户名只能为字母数字,请重试。', {
skin: 'layui-layer-molv'
,closeBtn: 0
,anim: 1
,btn: ['确定']
,icon: 2
});
} else if(data.ret == -3){
layer.alert('本站关闭了注册功能。', {
skin: 'layui-layer-molv'
,closeBtn: 0
,anim: 1
,btn: ['确定']
,icon: 2
});
}else if(data.ret == -4){
layer.alert('非法注册,请刷新页面后重新尝试。', {
skin: 'layui-layer-molv'
,closeBtn: 0
,anim: 1
,btn: ['确定']
,icon: 2
});
}else {
layer.alert('注册失败,请重试。', {
skin: 'layui-layer-molv'
,closeBtn: 0
,anim: 1
,btn: ['确定']
,icon: 2
});
}
setTimeout(function () {
}, 2000);
}
again(2);
$("#userzc").css('display','block');
$("#zctishi").css('display','none');
}
});
}else{
shakeModal(6);
$("#userzc").css('display','block');
$("#zctishi").css('display','none');
}
}
//登录
function loginAjax() {
var loginemail = $("#loginemail").val();
var loginpassword = $("#loginpassword").val();
if(verification){
//验证成功
$.ajax({
type: "POST",
url: "/user/login",
data: {email: loginemail, password: loginpassword,logotmp:logotmp},
dataType: "json",
success: function (data) {
$('#loginModal').modal('hide');
if (data == 1) {
//toastr.success("登录成功");
//$.cookie('name_hellohaobycookie', loginemail, { expires: 90});
//$.cookie('pass_hellohaobycookie', loginpassword, { expires: 90});
//$.cookie('Hellohao_UniqueUserKey', loginpassword, { expires: 90});
layer.msg('登录成功', {icon: 1});
setTimeout(function () {
window.location.reload();
}, 1000);
} else {
if (data == -1) {
//$('#dlts').text('您的账号是未激活状态,无法登陆。');
//toastr.error('您的账号是未激活状态,无法登陆。');
layer.msg('此账号是未激活状态,无法登陆', {icon: 4});
again();
} else if(data==-2){
//$('#dlts').text('您的账号已被冻结。');
layer.msg('您的账号已被冻结', {icon: 2});
again(1);
}else if(data==-3){
//$('#dlts').text('非法登录,请刷新页面重新尝试。');
layer.msg('非法登录,请刷新页面重新尝试', {icon: 2});
again(1);
}
else {
//$('#dlts').text('登录失败,你的邮箱或密码不正确');
layer.msg('登录失败,邮箱或者密码不正确', {icon: 2});
again(1);
}
setTimeout(function () {
//window.location.reload();
}, 2000);
}
}
});
}else{
$('#dlts').text('请滑动验证码进行验证,才可登录。');
}
}
function imgsc() {
var str = '输入图片URL地址:';
if(isday>0){
str = '输入图片URL地址:('+isday+'天后将会自动销毁)';
}
swal(str, {
content: "input",
})
.then((value) => {
var result =value;
if(result!=null && result!="" ){
urlimg(result);
}
});
}
function copyText() {
var data = data = $('#urls').val();
var copy = new ClipboardJS('.copytext', {
text: function (trigger) {
return data;
}
});
copy.on('success', function (e) {
layer.msg('复制成功');
copy.off("success");
});
copy.on('error', function (e) {
layer.msg('复制失败');
copy.off("error");
});
}
function loadScriptString(code) {
var script = document.createElement("script");
script.type = "text/javascript";
try {
// firefox、safari、chrome和Opera
script.appendChild(document.createTextNode(code));
} catch (ex) {
// IE早期的浏览器 ,需要使用script的text属性来指定javascript代码。
script.text = code;
}
document.getElementsByTagName("head")[0].appendChild(script);
}
function urlimg(result) {
if(result) {
var rx=/^https?:\/\//i;
if(rx.test(result)==true){
var msgid = layer.msg('上传中..', {
icon: 16
,shade: 0.01
});
//qq = GetDateStr(new Date());
qq = $('#vu').val();
$('#loadingModal').modal({backdrop: 'static', keyboard: false,upurlk:qq});
$.ajax({
type: "POST",
url: "/upurlimg",
dataType: "json",
data: {imgurl: result,setday:isday,upurlk:qq},
success: function (data) {
layer.close(msgid);
for(var i=0;i<data.length;i++){
if(data[i]==-1){
$('#loadingModal').modal('hide');
swal('上传失败', '未配置存储源,请先后台配置存储源');
}
else if(data[i]==-2){
$('#loadingModal').modal('hide');
swal('上传失败', '图片太大或不存在');
}
else if(data[i]==-3){
$('#loadingModal').modal('hide');
swal('上传失败', '文件类型不符合要求');
}
else if(data[i]==-4){
$('#loadingModal').modal('hide');
swal('上传失败', '该文件不支持上传');
}else if(data[i]==-5){
$('#loadingModal').modal('hide');
swal('上传失败,可用空间不足');
}else if(data[i]==403){
$('#loadingModal').modal('hide');
swal('非法调用,请刷新页面后重试');
}else if(data[i]==911){
$('#loadingModal').modal('hide');
swal('你目前不能上传图片,请联系管理员');
}else{
$('#loadingModal').modal('hide');
swal('上传成功', '该图片链接已成功上传');
$("#address").css('display', 'block');
arr_url += data[i] + '\r\n';
arr_markdown += '![ ](' + data[i] + ')\r\n';
arr_html += '<img src="' + data[i] + '" alt="Image" title="Image" /> \r\n';
arr_ddcode +='[img]'+data[i]+'[/img]\r\n';
}
if(urltypes==1){
$("#urls").text(arr_url);
}else if(urltypes==2){
$("#urls").text(arr_markdown);
}else if(urltypes==3){
$("#urls").text(arr_html);
}else{
$("#urls").text(arr_ddcode);
}
}
}
});
}else{layer.close(msgid);Popups('网址格式错误','网址必须以http(s)://开头。','error');}
}
}
function Popups(str1,str2,types) {
swal({
title: str1,
text: str2,
type: types,
showCancelButton: false,//true显示两个按钮
confirmButtonColor: "#A5DC86",
confirmButtonText: "知道了",
closeOnConfirm: true,
closeOnCancel: false
});
}
function urltype(urltypes){
if(urltypes==1){
$("#urls").text(arr_url);
}else if(urltypes==2){
$("#urls").text(arr_markdown);
}else if(urltypes==3){
$("#urls").text(arr_html);
}else{
$("#urls").text(arr_ddcode);
}
}
//获取当前时间
function clock(){
now = new Date();
year = now.getFullYear();
month = now.getMonth() + 1;
day = now.getDate();
today = ['星期日','星期一','星期二','星期三','星期四','星期五','星期六'];
week = today[now.getDay()];
hour = now.getHours();
min = now.getMinutes();
sec = now.getSeconds();
if (hour < 10) {
hour = "0" + hour;
}
if (min < 10) {
min = "0" + min;
}
if (sec < 10) {
sec = "0" + sec;
}
if (day < 10) {
day = "0" + day;
}
//$("#nian").html(year);
//$("#yue").html(month);
$("#ri").html(day);
$("#shi").html(hour);
$("#fen").html(min);
$("#miao").html(sec);
}
function xiazai(){
swal({
title: "即将下载客户端",
text: "客户端目前持支Windows系统其他系统请勿下载",
icon: "success",
buttons: true,
buttons: ["取消", "下载"],
dangerMode: false,
})
.then((value) => {
if (value) {
window.open("http://img.wwery.com/HellohaoApps/PC/Hellohao%E5%9B%BE%E5%BA%8A_beta.exe");
} else {
}
});
}
//回车登录
function keyLogin(){
if (event.keyCode==13)
document.getElementById("dl").click();
}
//网站退出
function exit() {
$.ajax({
type: "POST",
url: "/user/exit.do",
dataType: "json",
success: function (data) {
$.cookie('name_hellohaobycookie', null);
$.cookie('pass_hellohaobycookie', null);
layer.msg('账号已退出', {icon: 1});
window.location.reload();
}
});
}
+3
View File
@@ -0,0 +1,3 @@
/*! jquery.cookie v1.4.1 | MIT */
!function(a){"function"==typeof define&&define.amd?define(["jquery"],a):"object"==typeof exports?a(require("jquery")):a(jQuery)}(function(a){function b(a){return h.raw?a:encodeURIComponent(a)}function c(a){return h.raw?a:decodeURIComponent(a)}function d(a){return b(h.json?JSON.stringify(a):String(a))}function e(a){0===a.indexOf('"')&&(a=a.slice(1,-1).replace(/\\"/g,'"').replace(/\\\\/g,"\\"));try{return a=decodeURIComponent(a.replace(g," ")),h.json?JSON.parse(a):a}catch(b){}}function f(b,c){var d=h.raw?b:e(b);return a.isFunction(c)?c(d):d}var g=/\+/g,h=a.cookie=function(e,g,i){if(void 0!==g&&!a.isFunction(g)){if(i=a.extend({},h.defaults,i),"number"==typeof i.expires){var j=i.expires,k=i.expires=new Date;k.setTime(+k+864e5*j)}return document.cookie=[b(e),"=",d(g),i.expires?"; expires="+i.expires.toUTCString():"",i.path?"; path="+i.path:"",i.domain?"; domain="+i.domain:"",i.secure?"; secure":""].join("")}for(var l=e?void 0:{},m=document.cookie?document.cookie.split("; "):[],n=0,o=m.length;o>n;n++){var p=m[n].split("="),q=c(p.shift()),r=p.join("=");if(e&&e===q){l=f(r,g);break}e||void 0===(r=f(r))||(l[q]=r)}return l};h.defaults={},a.removeCookie=function(b,c){return void 0===a.cookie(b)?!1:(a.cookie(b,"",a.extend({},c,{expires:-1})),!a.cookie(b))}});

Some files were not shown because too many files have changed in this diff Show More