<file_sep>package com.azxx.picture.entity;

import javax.persistence.Id;
import java.util.Date;

public class GroupInfo {
    /**
     * This field was generated by MyBatis Generator.
     * This field corresponds to the database column group_info.id
     *
     * @mbggenerated
     */
    @Id
    private Integer id;

    /**
     * This field was generated by MyBatis Generator.
     * This field corresponds to the database column group_info.desc
     *
     * @mbggenerated
     */
    private String description;

    /**
     * This field was generated by MyBatis Generator.
     * This field corresponds to the database column group_info.name
     *
     * @mbggenerated
     */
    private String name;

    /**
     * This field was generated by MyBatis Generator.
     * This field corresponds to the database column group_info.record_time
     *
     * @mbggenerated
     */
    private Date recordTime;

    /**
     * This method was generated by MyBatis Generator.
     * This method returns the value of the database column group_info.id
     *
     * @return the value of group_info.id
     *
     * @mbggenerated
     */
    public Integer getId() {
        return id;
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method sets the value of the database column group_info.id
     *
     * @param id the value for group_info.id
     *
     * @mbggenerated
     */
    public void setId(Integer id) {
        this.id = id;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method returns the value of the database column group_info.name
     *
     * @return the value of group_info.name
     *
     * @mbggenerated
     */
    public String getName() {
        return name;
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method sets the value of the database column group_info.name
     *
     * @param name the value for group_info.name
     *
     * @mbggenerated
     */
    public void setName(String name) {
        this.name = name == null ? null : name.trim();
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method returns the value of the database column group_info.record_time
     *
     * @return the value of group_info.record_time
     *
     * @mbggenerated
     */
    public Date getRecordTime() {
        return recordTime;
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method sets the value of the database column group_info.record_time
     *
     * @param recordTime the value for group_info.record_time
     *
     * @mbggenerated
     */
    public void setRecordTime(Date recordTime) {
        this.recordTime = recordTime;
    }
}<file_sep>package com.azxx.picture.configuration;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.servlet.config.annotation.ContentNegotiationConfigurer;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.nio.charset.Charset;
import java.util.List;

/**
 * @version V1.0
 * @class: CustomWebMvcConfigurerAdapter
 * @description:
 * @author: xuzheng
 * @create: 2019-02-03 09:17
 **/
@Configuration
public class CustomWebMvcConfigurerAdapter implements WebMvcConfigurer {

    @Value("${img.dir}")
    private String localpath;

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        //将templates目录下的CSS、JS文件映射为静态资源，防止Spring把这些资源识别成thymeleaf模版
        registry.addResourceHandler("/templates/**").addResourceLocations("classpath:/templates/");
        //其他静态资源
        registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
        //swagger增加url映射
        registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
        registry.addResourceHandler("/picture/**").addResourceLocations("file:"+localpath);
    }

    @Bean
    public HttpMessageConverter<String> responseBodyConverter() {
        StringHttpMessageConverter converter = new StringHttpMessageConverter(
                Charset.forName("UTF-8"));
        return converter;
    }
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
//        super.configureMessageConverters(converters);
        converters.add(responseBodyConverter());
    }
    @Override
    public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
        configurer.favorPathExtension(false);
    }
}
<file_sep>package com.azxx.picture.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.azxx.picture.vo.AppInfoVo;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ResourceLoader;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import com.azxx.picture.entity.AppInfo;
import com.azxx.picture.entity.FileInfo;
import com.azxx.picture.service.FileService;
import com.azxx.picture.vo.OperateTypeEm;
import com.azxx.picture.vo.fileInfo.FileReqVo;
import com.github.pagehelper.PageInfo;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;

/**
 * @version V1.0
 * @class: PictureController
 * @description: 图片操作、查询类
 * @author: xuzheng
 * @create: 2019-02-02 10:08
 **/

@RestController
@RequestMapping(path = "/apps")
@Api(tags = "apps", description = "图片管理")
public class FileController extends BaseController {
    private static final Logger logger = LoggerFactory.getLogger(FileController.class);

    @Autowired
    private FileService fileService;


    private final ResourceLoader resourceLoader;

    @Value("${img.dir}")
    private String filePath;

    @Value("${img.url}")
    private String imgUrl;

    @Value("${img.imgName}")
    private String imgName;

    @Autowired
    public FileController(ResourceLoader resourceLoader) {
        this.resourceLoader = resourceLoader;
    }

    @RequestMapping(path = "/uploadFile", method = RequestMethod.PUT)
    @ApiOperation(value = "文件上传", notes = "文件上传")
    @ApiResponses({@ApiResponse(code = 200, message = "处理成功")})
    public String uploadFile(@RequestParam("fileToUpload") MultipartFile file, AppInfo appInfo) {

//        String fileType = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        try {
            if (null == appInfo.getAppId()) {
                return paramsError();
            }
            String pathName = filePath + appInfo.getAppId() + "/" + imgName;
            String imgFilePath = filePath + appInfo.getAppId();
            File imgFilePath1 = new File(imgFilePath);
            if (!imgFilePath1.exists()) {
                imgFilePath1.mkdirs();
            }
            File tmpFile = new File(pathName);
            if (!tmpFile.exists()) {
                tmpFile.createNewFile();
            }
            InputStream in = file.getInputStream();
            FileOutputStream fos = new FileOutputStream(tmpFile);
            byte[] b = new byte[1024];
            int length;
            while ((length = in.read(b)) != -1) {
                fos.write(b, 0, length);
            }
            in.close();
            fos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return queryOk(null);
    }

    @RequestMapping(path = "", method = RequestMethod.GET)
    @ApiOperation(value = "分页获取微应用信息", notes = "分页获取微应用信息")
    @ApiResponses({@ApiResponse(code = 200, message = "处理成功", response = AppInfo.class)})
    public String getFiles(AppInfoVo appInfoVo) {

        if (appInfoVo == null) {
            return paramsError();
        }
        try {
            PageInfo<AppInfo> result = fileService.getFiles(appInfoVo);
            return queryOk(result);
        } catch (Exception e) {
            e.printStackTrace();
            return error(null, OperateTypeEm.QUERY.toString());
        }

    }

    @RequestMapping(path = "", method = RequestMethod.POST)
    @ApiOperation(value = "增加或更新微应用管理信息", notes = "增加或更新微应用管理信息")
    @ApiResponses({@ApiResponse(code = 200, message = "处理成功", response = FileInfo.class)})
    public String addOrUpdateFile(AppInfoVo appInfoVo) {
        if (appInfoVo == null || StringUtils.isBlank(appInfoVo.getAppId())) {
            return paramsError();
        }

        logger.info("增加或更新图片信息，参数：{}", JSON.toJSON(appInfoVo));
        try {
            appInfoVo.setState(appInfoVo.getStateName());
            System.err.println(appInfoVo.getState());
            boolean result = fileService.insertOrUpdateFile(appInfoVo);
            if (result) {
                return updateOk(null);
            } else {
                return paramsError();
            }
        } catch (Exception e) {
            e.printStackTrace();
            return error(null, OperateTypeEm.UPDATE.toString());
        }
    }

    @RequestMapping(path = "/selectState", method = RequestMethod.GET)
    @ApiOperation(value = "查询微应用状态", notes = "查询微应用状态")
    @ApiResponses({@ApiResponse(code = 200, message = "处理成功", response = FileInfo.class)})
    public String selectState() {

        List<AppInfo> list = fileService.selectState();
        return queryOk(list);
    }

    /**
     * 显示单张图片
     *
     * @return
     */
    @RequestMapping(path = "/show", method = RequestMethod.GET)
    public ResponseEntity showPhotos(String fileName) {

        try {
            // 由于是读取本机的文件，file是一定要加上的， path是在application配置文件中的路径
            return ResponseEntity.ok(resourceLoader.getResource("file:" + Paths.get("D:\\newcoding\\pricterManage\\src\\main\\resources\\static\\customer\\img", "bbbbbbb.jpg").toString()));
        } catch (Exception e) {
            return ResponseEntity.notFound().build();
        }
    }

//    @RequestMapping(path = "/pages", method = RequestMethod.POST)
//    @ApiOperation(value = "获取图片列表", notes = "获取图片列表")
//    @ApiResponses({@ApiResponse(code = 200, message = "处理成功", response = FileInfo.class)})
//    public String pages(FileReqVo reqVo) {
//
//        if (reqVo == null) {
//            return paramsError();
//        }
//
//        logger.info("获取文件列表开始，参数：{}", JSON.toJSON(reqVo));
//        try {
//            PageInfo<FileInfo> result = fileService.pages(reqVo);
//            return queryOk(result);
//        } catch (Exception e) {
//            e.printStackTrace();
//            return error(null, OperateTypeEm.QUERY.toString());
//        }
//
//    }

//    @RequestMapping(path = "/uploadFile", method = RequestMethod.POST)
//    @ApiOperation(value = "文件上传", notes = "文件上传")
//    @ApiResponses({@ApiResponse(code = 200, message = "处理成功")})
//    public String uploadFile(@RequestParam("fileToUpload") MultipartFile file, FileReqVo reqVo, HttpServletRequest request) {
//        if (reqVo == null) {
//            return paramsError();
//        }
//        String fileName = file.getOriginalFilename();
//        reqVo.setSize((int) (file.getSize() / 1000));
//        if (StringUtils.isBlank(reqVo.getName())) {
//            reqVo.setName(fileName);
//        }
//        if (StringUtils.isBlank(reqVo.getTitle())) {
//            reqVo.setName(fileName);
//        }
//        if (fileName.indexOf(".") > -1) {
//            reqVo.setType(fileName.substring(fileName.lastIndexOf(".")));
//        }
//        reqVo.setUrl(imgUrl+reqVo.getName());
//        try {
//            String pathname = filePath + reqVo.getName();
//            if(reqVo.getName().indexOf(reqVo.getType())<0){
//                reqVo.setUrl(imgUrl+reqVo.getName()+reqVo.getType());
//                pathname = filePath + reqVo.getName()+reqVo.getType();
//            }
//            fileService.addOrUpdateFile(reqVo);
//            String url = request.getContextPath();
//            logger.info("绝对路径：{}，工程路径：{}", filePath, url);
//            File tmpFile = new File(pathname);
//            if (!tmpFile.exists()) {
//                tmpFile.createNewFile();
//            }
//            InputStream in = file.getInputStream();
//            FileOutputStream fos = new FileOutputStream(tmpFile);
//            byte[] b = new byte[1024];
//            int length;
//            while ((length = in.read(b)) != -1) {
//                fos.write(b, 0, length);
//            }
//            in.close();
//            fos.close();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        return queryOk(null);
//    }
//

//
//    @RequestMapping(path = "/deleteFile", method = RequestMethod.POST)
//    @ApiOperation(value = "删除图片信息", notes = "删除图片信息")
//    @ApiResponses({@ApiResponse(code = 200, message = "处理成功", response = FileInfo.class)})
//    public String deleteFile(String id) {
//        if (StringUtils.isBlank(id)) {
//            return paramsError();
//        }
//        logger.info("删除图片信息，参数：{}", id);
//        try {
//            fileService.deleteFile(id);
//            return updateOk(null);
//        } catch (Exception e) {
//            e.printStackTrace();
//            return error(null, OperateTypeEm.UPDATE.toString());
//        }
//    }

}
<file_sep># thyeme

Thymeleaf 是一种模板语言。那模板语言或模板引擎是什么？常见的模板语言都包含以下几个概念：数据（Data）、模板（Template）、模板引擎（Template Engine）和结果文档（Result Documents）。

- 数据：数据是信息的表现形式和载体，可以是符号、文字、数字、语音、图像、视频等。数据和信息是不可分离的，数据是信息的表达，信息是数据的内涵。数据本身没有意义，数据只有对实体行为产生影响时才成为信息。
- 模板：模板，是一个蓝图，即一个与类型无关的类。编译器在使用模板时，会根据模板实参对模板进行实例化，得到一个与类型相关的类。
- 模板引擎：模板引擎（这里特指用于Web开发的模板引擎）是为了使用户界面与业务数据（内容）分离而产生的，它可以生成特定格式的文档，用于网站的模板引擎就会生成一个标准的HTML文档。
- 结果文档：一种特定格式的文档，比如用于网站的模板引擎就会生成一个标准的HTML文档。

模板语言用途广泛，常见的用途如下
- 页面渲染
- 文档生成
- 代码生成
- 所有 “数据+模板=文本” 的应用场景

# 集成

## 添加依赖

```
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
```

## 创建目录
* resources/static：存放css、js等资源文件
* resources/templates：存放视图模板文件

## 配置添加

```
spring:
    thymeleaf:
        cache: true  # Enable template caching.
        check-template: true # Check that the template exists before rendering it.
        check-template-location: true # Check that the templates location exists.
        enabled: true # Enable Thymeleaf view resolution for Web frameworks.
        encoding: UTF-8 # Template files encoding.
        excluded-view-names:  # Comma-separated list of view names that should be excluded from resolution.
        mode: HTML5 # Template mode to be applied to templates. See also StandardTemplateModeHandlers.
        prefix: classpath:/templates/ # Prefix that gets prepended to view names when building a URL.
        suffix: .html # Suffix that gets appended to view names when building a URL.
        template-resolver-order:  # Order of the template resolver in the chain.
        view-names:  # Comma-separated list of view names that can be resolved.
        reactive:
            max-chunk-size:  # Maximum size of data buffers used for writing to the response, in bytes.
            media-types:  # Media types supported by the view technology.
        servlet:
            content-type: text/html # Content-Type value written to HTTP responses.

```
```
spring.thymeleaf.cache=true # Enable template caching.
spring.thymeleaf.check-template=true # Check that the template exists before rendering it.
spring.thymeleaf.check-template-location=true # Check that the templates location exists.
spring.thymeleaf.enabled=true # Enable Thymeleaf view resolution for Web frameworks.
spring.thymeleaf.encoding=UTF-8 # Template files encoding.
spring.thymeleaf.excluded-view-names= # Comma-separated list of view names that should be excluded from resolution.
spring.thymeleaf.mode=HTML5 # Template mode to be applied to templates. See also StandardTemplateModeHandlers.
spring.thymeleaf.prefix=classpath:/templates/ # Prefix that gets prepended to view names when building a URL.
spring.thymeleaf.reactive.max-chunk-size= # Maximum size of data buffers used for writing to the response, in bytes.
spring.thymeleaf.reactive.media-types= # Media types supported by the view technology.
spring.thymeleaf.servlet.content-type=text/html # Content-Type value written to HTTP responses.
spring.thymeleaf.suffix=.html # Suffix that gets appended to view names when building a URL.
spring.thymeleaf.template-resolver-order= # Order of the template resolver in the chain.
spring.thymeleaf.view-names= # Comma-separated list of view names that can be resolved.
```<file_sep># 图片管理系统

## 技术参数

* SpringBoot
* mybatis
* druid
* thymeleaf
* bootstrap
* swagger-ui


<file_sep><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <!-- Inherit defaults from Spring Boot -->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.5.RELEASE</version>
        <relativePath></relativePath>
    </parent>

    <groupId>com.azxx.system</groupId>
    <artifactId>pictureManage</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>
    <name>pictureManage</name>
    <description> pictrue manage system</description>


    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <swagger.version>2.7.0</swagger.version>
        <druid.version>1.1.13</druid.version>
        <mybatis.version>2.0.0</mybatis.version>
        <tk.mybatis.versiong>2.1.5</tk.mybatis.versiong>
        <mysql.version>8.0.12</mysql.version>
        <pagehelper.version>5.1.8</pagehelper.version>
        <pagehelper.starter.version>1.2.10</pagehelper.starter.version>
        <httpclient.version>4.5.6</httpclient.version>
        <fastjson.version>1.2.56</fastjson.version>
        <gson.version>2.8.5</gson.version>
        <commons.lang3.version>3.8.1</commons.lang3.version>
    </properties>

    <!-- Add typical dependencies for a web application -->
    <dependencies>
    	<!-- 排除内置tomcat -->
	    <!-- <dependency>
		        <groupId>org.springframework.boot</groupId>
		        <artifactId>spring-boot-starter-tomcat</artifactId>
		        <scope>provided</scope>
		</dependency> -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!--test-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <optional>true</optional>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
        </dependency>

        <!--thymeleaf-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>

        <!--swagger ui-->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>${swagger.version}</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>${swagger.version}</version>
        </dependency>

        <!-- JDBC -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>${druid.version}</version>
        </dependency>

        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>${mybatis.version}</version>
        </dependency>

        <!--mapper -->
        <dependency>
            <groupId>tk.mybatis</groupId>
            <artifactId>mapper-spring-boot-starter</artifactId>
            <version>${tk.mybatis.versiong}</version>
        </dependency>

        <!--pagehelper -->
        <!--<dependency>-->
            <!--<groupId>com.github.pagehelper</groupId>-->
            <!--<artifactId>pagehelper</artifactId>-->
            <!--<version>${pagehelper.version}</version>-->
        <!--</dependency>-->
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper-spring-boot-starter</artifactId>
            <version>${pagehelper.starter.version}</version>
        </dependency>

        <!-- mysql -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>${mysql.version}</version>
        </dependency>

        <!-- httpclient -->
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>${httpclient.version}</version>
        </dependency>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>${fastjson.version}</version>
        </dependency>

        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>${gson.version}</version>
        </dependency>

        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>${commons.lang3.version}</version>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <fork>true</fork>
                    <mainClass>com.azxx.picture.Starter</mainClass>
                </configuration>
            </plugin>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <encoding>UTF-8</encoding>
                    <!--<compilerArguments> -->
                    <!--<bootclasspath>${java.home}\lib\rt.jar;${java.home}\lib\jce.jar</bootclasspath> -->
                    <!--<bootclasspath>/data/java/jdk1.8.0_131/lib/rt.jar;/data/java/jdk1.8.0_131/lib/jce.jar</bootclasspath> -->
                    <!--</compilerArguments> -->
                </configuration>
            </plugin>

            <plugin>
                <groupId>org.mybatis.generator</groupId>
                <artifactId>mybatis-generator-maven-plugin</artifactId>
                <version>1.3.2</version>
                <dependencies>
                    <dependency>
                        <groupId>org.mybatis.generator</groupId>
                        <artifactId>mybatis-generator-core</artifactId>
                        <version>1.3.2</version>
                    </dependency>
                    <dependency>
                        <groupId>mysql</groupId>
                        <artifactId>mysql-connector-java</artifactId>
                        <version>8.0.14</version>
                    </dependency>
                </dependencies>
            </plugin>
        </plugins>
    </build>

</project><file_sep># 集成

## 添加依赖

```
<!--swagger ui-->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>${swagger.version}</version>
</dependency>
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>${swagger.version}</version>
</dependency>
```

## 配置

```
@Configuration
@EnableSwagger2
public class SwaggerConfig {

    @Bean
    public Docket config() {
        return new Docket(DocumentationType.SWAGGER_2)
                .enable(true)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.azxx.picture.controller"))
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder().title("图片管理系统-api文档").description("图片管理系统-api文档").termsOfServiceUrl("").version("1.0.0").build();
    }
}
```

## 访问

```
http://localhost:8080/swagger-ui.html
```

# 注解详解

## @Api

该注解将一个Controller（Class）标注为一个swagger资源（API）。在默认情况下，Swagger-Core只会扫描解析具有@Api注解的类，而会自动忽略其他类别资源（JAX-RS endpoints，Servlets等等）的注解。该注解包含以下几个重要属性：

- tags API分组标签。具有相同标签的API将会被归并在一组内展示。
- value 如果tags没有定义，value将作为Api的tags使用
- description API的详细描述，在1.5.X版本之后不再使用，但实际发现在2.0.0版本中仍然可以使用

## @ApiOperation

在指定的（路由）路径上，对一个操作或HTTP方法进行描述。具有相同路径的不同操作会被归组为同一个操作对象。不同的HTTP请求方法及路径组合构成一个唯一操作。此注解的属性有：

- value 对操作的简单说明，长度为120个字母，60个汉字。
- notes 对操作的详细说明。
- httpMethod HTTP请求的动作名，可选值有："GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS" and "PATCH"。
- code 默认为200，有效值必须符合标准的HTTP Status Code Definitions。

## @ApiImplicitParams

注解ApiImplicitParam的容器类，以数组方式存储。

## @ApiImplicitParam

对API的单一参数进行注解。虽然注解@ApiParam同JAX-RS参数相绑定，但这个@ApiImplicitParam注解可以以统一的方式定义参数列表，也是在Servelet及非JAX-RS环境下，唯一的方式参数定义方式。注意这个注解@ApiImplicitParam必须被包含在注解@ApiImplicitParams之内。可以设置以下重要参数属性：

- name 参数名称
- value 参数的简短描述
- required 是否为必传参数
- dataType 参数类型，可以为类名，也可以为基本类型（String，int、boolean等）
- paramType 参数的传入（请求）类型，可选的值有path, query, body, header or form

## @ApiParam

增加对参数的元信息说明。这个注解只能被使用在JAX-RS 1.x/2.x的综合环境下。其主要的属性有：

- required 是否为必传参数
- value 参数简短说明

## @ApiResponses

注解@ApiResponse的包装类，数组结构。即使需要使用一个@ApiResponse注解，也需要将@ApiResponse注解包含在注解@ApiResponses内。

## @ApiResponse

描述一个操作可能的返回结果。当REST API请求发生时，这个注解可用于描述所有可能的成功与错误码。可以用，也可以不用这个注解去描述操作的返回类型，但成功操作的返回类型必须在@ApiOperation中定义。如果API具有不同的返回类型，那么需要分别定义返回值，并将返回类型进行关联。但Swagger不支持同一返回码，多种返回类型的注解。注意：这个注解必须被包含在@ApiResponses注解中。

- code HTTP请求返回码。有效值必须符合标准的HTTP Status Code Definitions。
- message 更加易于理解的文本消息
- response 返回类型信息，必须使用完全限定类名，比如“com.xyz.cc.Person.class”
- responseContainer 如果返回类型为容器类型，可以设置相应的值。有效值为 "List", "Set" or "Map"，其他任何无效的值都会被忽略

## @ApiModel

提供对Swagger model额外信息的描述。在标注@ApiOperation注解的操作内，所有的类将自动被内省（introspected），但利用这个注解可以做一些更加详细的model结构说明。主要属性有：

- value model的别名，默认为类名
- description model的详细描述

## @ApiModelProperty

对model属性的注解，主要的属性值有：

- value 属性简短描述
- example 属性的示例值
- required 是否为必须值

# 使用例子

```
@RestController
@RequestMapping(path = "/fileManage")
@Api(tags = "FileManage", description = "图片管理")
public class FileController extends  BaseController{
    private static final Logger logger = LoggerFactory.getLogger(FileController.class);

    @Autowired
    private FileService fileService;

    @RequestMapping(path = "/getFiles",method = RequestMethod.POST)
    @ApiOperation(value = "获取图片列表" ,notes = "获取图片列表")
    @ApiResponses({ @ApiResponse(code = 200, message = "处理成功", response = FileInfo.class) })
    public String getFiles(FileReqVo reqVo){

        if(reqVo == null){
            return paramsError();
        }

        logger.info("获取文件列表开始，参数：{}", JSON.toJSON(reqVo));
        try {
            List<FileInfo> result = fileService.getFiles(reqVo);
            return  queryOk(result);
        }catch (Exception e){
            e.printStackTrace();
            return  error(null,OperateTypeEm.QUERY.toString());
        }

    }
 }
```<file_sep>CREATE DATABASE `picture_manage` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;

CREATE TABLE `file_info` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(100) NULL COMMENT '文件名称',
`title` varchar(200) NULL COMMENT '相片标题',
`description` varchar(1000) NULL COMMENT '描述',
`size` int(11) NULL COMMENT '文件大小',
`type` varchar(50) NULL COMMENT '文件类型ID',
`group_id` int(11) NULL COMMENT '分组ID',
`group_name` varchar(100) NULL COMMENT '分组名称',
`url` varchar(255) NULL COMMENT '路径',
`create_time` timestamp(0) NULL  COMMENT '文件创建时间',
`record_time` timestamp(0) NULL COMMENT '记录时间',
PRIMARY KEY (`id`) 
);

CREATE TABLE `group_info` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`description` varchar(255) NULL COMMENT '分组描述',
`name` varchar(255) NULL COMMENT '分组名称',
`record_time` timestamp NULL COMMENT '记录时间',
PRIMARY KEY (`id`) 
);<file_sep>package com.azxx.picture.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;

@Component
public class EmailService {

    private static Logger logger = LoggerFactory.getLogger(EmailService.class);

    @Autowired
    private JavaMailSender mailSender;

    @Value("${email.emailFrom}")
    private String emailFrom;

    /**
     *
     * @param emailTo 邮件发送地址
     * @param subject 主题
     * @param content 内容
     */
    public void sendSimpleEmail(String emailTo,String subject,String content){
        SimpleMailMessage message = new SimpleMailMessage();

        message.setFrom(emailFrom);
        message.setTo(emailTo);

        //同时发送邮件给多人
//        String[] adds = {"<EMAIL>","<EMAIL>"};
//        message.setTo(adds);
        message.setSubject(subject);
        message.setText(content);
        try {
            mailSender.send(message);
            logger.info("email send successful!");
        } catch (Exception e) {
            logger.info("email send failure!",e);
        }
    }

    /**
     *  发送HTML邮件
     * @param emailTo  要发送的邮件地址
     * @param subject 主题
     * @param content 内容
     */
    public void sendHtmlEmail(String emailTo,String subject,String content){
        MimeMessage message = mailSender.createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(message,true);
            helper.setFrom(emailFrom);
            helper.setTo(emailTo);
            helper.setSubject(subject);
            helper.setText(content,true);

            mailSender.send(message);
            logger.info("email send successful!");
        } catch (MessagingException e) {
            logger.info("email send failure!",e);
        }
    }

    /**
     *  发送带附件的邮件
     * @param to 要发送的邮件地址
     * @param subject 主题
     * @param content 内容
     * @param filePath 附件地址
     */
    public void sendAttachmentsEmail(String to, String subject, String content, String filePath) {

        //创建一个MINE消息
        MimeMessage message = mailSender.createMimeMessage();

        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(emailFrom);
            helper.setTo(to);
            helper.setSubject(subject);
            // true表示这个邮件是有附件的
            helper.setText(content, true);

            //创建文件系统资源
            FileSystemResource file = new FileSystemResource(new File(filePath));
            String fileName = filePath.substring(filePath.lastIndexOf(File.separator));
            //添加附件
            helper.addAttachment(fileName, file);

            mailSender.send(message);
            logger.info("带附件的邮件已经发送。");
        } catch (MessagingException e) {
            logger.error("发送带附件的邮件时发生异常！", e);
        }
    }

    /**
     *  发送嵌入静态资源的邮件
     * @param to 要发送的邮件地址
     * @param subject 主题
     * @param content 内容
     * @param rscPath 资源路径
     * @param rscId 资源ID
     */
    public void sendInlineResourceEmail(String to, String subject, String content, String rscPath, String rscId) {
        MimeMessage message = mailSender.createMimeMessage();

        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(emailFrom);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true);

            FileSystemResource res = new FileSystemResource(new File(rscPath));

            //添加内联资源，一个id对应一个资源，最终通过id来找到该资源
            helper.addInline(rscId, res);//添加多个图片可以使用多条 <img src='cid:" + rscId + "' > 和 helper.addInline(rscId, res) 来实现

            mailSender.send(message);
            logger.info("嵌入静态资源的邮件已经发送。");
        } catch (MessagingException e) {
            logger.error("发送嵌入静态资源的邮件时发生异常！", e);
        }

    }
}
<file_sep>package com.azxx.picture.vo;

/**
 * @version V1.0
 * @class: ResultCodeEm
 * @description:
 * @author: xuzheng
 * @create: 2019-02-02 11:27
 **/
public enum ResultCodeEm {

    UPDATE_SUCCESS("200","修改成功！"),

    QUERY_SUCCESS("200","查询成功！"),

    DELETE_SUCCESS("200","删除成功！"),

    UPDATE_FIALURE("500","修改失败！"),

    QUERY_FIALURE("500","查询失败！"),

    DELETE_FIALURE("500","删除失败！"),

    PARAMS_ERROR("500","参数错误!")
    ;

    ResultCodeEm(String code, String msg) {
        this.code = code;
        this.msg = msg;
    }

    private String code;

    private String msg;

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }
}
<file_sep>var grid_selector = "#grid-table";
var pager_selector = "#grid-pager";
var startTime = "";
var endTime = "";
var dateFormat = "YYYY-MM-DD HH:MM:SS";

var fileManage = {
    query: function () {
        $(grid_selector).jqGrid('clearGridData');  //清空表格
        $(grid_selector).jqGrid('setGridParam', {  // 重新加载数据
            postData: {
                appName: $("#appName").val(),
                startTime: startTime,
                endTime: endTime,
//                state: $("#state").val()
            },   //  newdata 是符合格式要求的需要重新加载的数据
        }).trigger("reloadGrid");
    },

    reset: function () {
        $(grid_selector).jqGrid('clearGridData');  //清空表格
        $("#timeRange").val("请选择日期");
        $("#appName").val("")
        startTime = "",
            endTime = "",
            $(grid_selector).jqGrid('setGridParam', {  // 重新加载数据
                postData: {
                    appName: "",
                    startTime: "",
                    endTime: "",
                },
            }).trigger("reloadGrid");
    },

    getSelect: function () {
        var options = "";
        $.ajax({
            url: baseUrl + "/groupManage/getGroups",
            type: "POST",
            async: false,
            data: {},
            success: function (response) {
                var data = $.parseJSON(response);
                if (data.code == 200) {
                    if (data.data != null && data.data.length > 0) {
                        for (var i = 0; i < data.data.length; i++) {
                            var tmp = data.data[i];
                            if (i != data.data.length - 1) {
                                options += tmp.name + ":" + tmp.name + ";";
                            } else {
                                options += tmp.name + ":" + tmp.name;
                            }

                        }

                    } else {
                        options += "无:无";
                    }
                }
            }
        });
        return options;
    },
    initGroup: function () {
        var self = this;
        $.ajax({
            url: baseUrl + "/groupManage/getGroups",
            type: "POST",
            data: {},
            success: function (response) {
                var data = $.parseJSON(response);
                if (data.code == 200) {
                    if (data.data != null && data.data.length > 0) {
                        $("#state").empty();
                        $("#state").append("<option value=''>全部</option>");
                        for (var i = 0; i < data.data.length; i++) {
                            var tmp = data.data[i];
                            $("#state").append("<option value='" + tmp.name + "'>" + tmp.name + "</option>");
                        }
                    }
                }
                if (data.status == "error") {
                    alert(data.msg);
                }
            },
            error: function () {
                alert("请求失败！");
            }
        });
    },
    enterEvent: function () {
        $(document).keydown(function (event) {
            if (event.keyCode == 13) {
                $(grid_selector).jqGrid('clearGridData');  //清空表格
                $(grid_selector).jqGrid('setGridParam', {  // 重新加载数据
                    postData: {
                        appName: $("#appName").val(),
                        startTime: startTime,
                        endTime: endTime,
                    },
                }).trigger("reloadGrid");
            }
        });
    },
    initGridData: function () {
        var self = this;
        jQuery(grid_selector).jqGrid({
            url: baseUrl + "/apps",
            datatype: "json",
            mtype: "get",
            postData: {},
            jsonReader: {
                root: "data.list",
                page: 10,
                total: "data.pages",
                records: "data.total"
            },
            colNames: ['id', '应用ID', '应用名称', '应用类型', '当前版本号', '区域', '当前状态', '发布日期', '操作', ''],
            colModel: [
                {name: 'id', index: 'id', width: 60, sorttype: "int", editable: true, edittype: 'text', hidden: true},
                {
                    name: 'appId',
                    index: 'appId',
                    width: 100,
                    editable: true,
                    edittype: 'text',
                    editoptions: {size: "20", maxlength: "100"}
                }, {
                    name: 'appName',
                    index: 'appName',
                    width: 100,
                    editable: true,
                    edittype: "text",
                    editoptions: {size: "20", maxlength: "100"}
                }, {
                    name: 'appType',
                    index: 'appType',
                    width: 50,
                    editable: false
                }, {
                    name: 'version',
                    index: 'version',
                    width: 50,
                    editable: true,
                    edittype: "text",
                    editoptions: {size: "20", maxlength: "100"}
                }, {
                    name: 'region',
                    index: 'region',
                    width: 100,
                    editable: false,
                    hidden: true
                }, {
                    name: 'stateName',
                    index: 'stateName',
                    width: 50,
                    editable: true,
                    edittype: "select",
                    editoptions: {style: "width:158.38px;height:37px", value: selectState()},
                    //formatter: fmatterFuuc

                }, {
                    name: 'releaseDate',
                    index: 'releaseDate',
                    width: 80,
                    sortable: false,
                    editable: false,
                    formatter: function (cellvalue, options, rowObject) {
                        var date = new Date();
                        date.setTime(cellvalue);
                        return date.Format("yyyy-MM-dd HH:mm:ss");
                    }
                }, {
                    name: '', index: '', width: 80, fixed: true, sortable: false, resize: false,
                    formatter: 'actions',
                    formatoptions: {
                        keys: true,
                        delbutton: false,//disable delete button
                        delOptions: {recreateForm: true, beforeShowForm: beforeDeleteCallback},
                        editformbutton: true,
                        editOptions: {
                            recreateForm: true,
                            closeAfterEdit: true,
                            beforeShowForm: beforeEditCallback,
                            beforeSubmit: beforeSumbitCallback,
                            afterSubmit: afterSubmitCallback
                        }
                    }
                }, {
                    name: 'fileToUpload',
                    index: 'fileToUpload',
                    hidden: true,
                    editoptions: {enctype: "multipart/form-data"},
                    edittype: 'file',
                    // formatter: this.showPicture,
                    width: 150,
                    align: "left",
                    editable: true
                }
            ],
            viewrecords: true,
            height: 'auto',
            width: 'auto',
            // height: 500,
            rowNum: 10,
            rowList: [10, 20, 50],
            pager: pager_selector,
            altRows: false,
            multiselect: false,
            multiboxonly: true,
            rownumbers: true,
            editurl: baseUrl + "/apps",//nothing is saved
            loadComplete: function () {
                var table = this;
                setTimeout(function () {
                    $(grid_selector).jqGrid('setLabel', 'rn', '序号', {'text-align': 'left'}, '');
                    styleCheckbox(table);
                    updateActionIcons(table);
                    updatePagerIcons(table);
                    enableTooltips(table);
                }, 0);
            }
        });
        $(window).triggerHandler('resize.jqGrid');//trigger window resize to make the grid get the correct size
        //navButtons
        jQuery(grid_selector).jqGrid('navGrid', pager_selector,
            { 	//navbar options
                edit: false,
                editicon: 'ace-icon fa fa-pencil blue',
                add: true,
                addicon: 'ace-icon fa fa-plus-circle purple',
                del: false,
                delicon: 'ace-icon fa fa-trash-o red',
                search: false,
                searchicon: 'ace-icon fa fa-search orange',
                refresh: true,
                refreshicon: 'ace-icon fa fa-refresh green',
                view: true,
                viewicon: 'ace-icon fa fa-search-plus grey',
            },
            {
                //edit record form
                closeAfterEdit: true,
                recreateForm: true,
                viewPagerButtons: true,
                beforeShowForm: function (e) {
                    var form = $(e[0]);
                    form.closest('.ui-jqdialog').find('.ui-jqdialog-titlebar').wrapInner('<div class="widget-header" />')
                    style_edit_form(form);

                    $("#editmodgrid-table").css("top", "20%");
                    $("#editmodgrid-table").css("left", "40%");
                },
                onInitializeForm: function (formid) {
                    var addUrl = baseUrl + "/apps";
                    console.log($(grid_selector).jqGrid('getGridParam', 'editurl'));
                    $(grid_selector).jqGrid('setGridParam', {editurl: addUrl});
                    $("#tr_fileToUpload").css("display", "");
                    console.log(formid);
//                     alert(postdata);
//                     $(formid).attr('method', 'POST');
                    // $(formid).attr('action', '/abc');
//                     $(formid).attr('enctype', 'multipart/form-data');
                },
                afterSubmit: function (response, postdata) {
                    var res = $.parseJSON(response.responseText);
                    if (res.code != 200) {
                        // self.uploadFile(postdata);
                        alert("提交失败，请重新提交！");
                        return [false];
                        // return [false, res.msg];
                    } else {
                        alert("图片上传成功！");
                        self.uploadFile(postdata);
                        return [true];
                    }
                }
            },
            {
                //new record form
                closeAfterAdd: true,
                recreateForm: true,
                viewPagerButtons: true,
                beforeShowForm: function (e) {
                    $("#editmodgrid-table").css("top", "20%");
                    $("#editmodgrid-table").css("left", "40%");
                    e.find("#appId").attr('readOnly', false);
                    // $(grid_selector).setGridParam().hideCol("fileToUpload").trigger("reloadGrid");
                    // $(grid_selector).setGridParam().showCol("fileToUpload").trigger("reloadGrid");
//                    var form = $(e[0]);
//                    form.closest('.ui-jqdialog').find('.ui-jqdialog-titlebar')
//                        .wrapInner('<div class="widget-header" />')
//                    style_edit_form(form);
                },
                onInitializeForm: function (formid) {
                    var addUrl = baseUrl + "/apps";
                    // console.log($(grid_selector).jqGrid('getGridParam', 'editurl'));
                    $(grid_selector).jqGrid('setGridParam', {editurl: addUrl});
                    $("#tr_fileToUpload").css("display", "");
                    // console.log(formid);
                    // $(formid).attr('method', 'POST');
                    // $(formid).attr('action', '/abc');
                    // $(formid).attr('enctype', 'multipart/form-data');
                },
                beforeSubmit: function beforeSumbit() {
                    var fileTypes = [".jpeg", ".png",".jpg", ".gif"];
                    var filePath = $('#fileToUpload').val();
                    if (filePath) {
                        var isNext = false;
                        var fileEnd = filePath.substring(filePath.indexOf("."));
                        for (var i = 0; i < fileTypes.length; i++) {
                            if (fileTypes[i] === fileEnd) {
                                isNext = true;
                                break;
                            }
                        }
                        if (!isNext) {
                            alert(" 只接受图片类型！");
                            return false;
                        }
                        return [true];
                    } else {
                        alert("请选择图片！")
                        return false;
                    }
                },

                afterSubmit: function (response, postdata) {
                    var res = $.parseJSON(response.responseText);
                    if (res.code != 200) {
                        // self.uploadFile(postdata);
                        alert("提交失败，请重新提交！");
                        return [false];
                        // return [false, res.msg];
                    } else {
                        //alert("图片上传成功！");
                        self.uploadFile(postdata);
                        return [true];
                    }
                }
            },
            {
                //delete record form
                recreateForm: true,
                onInitializeForm: function (formid) {
                    var delUrl = baseUrl + "/fileManage/deleteFile";
                    $(grid_selector).jqGrid('setGridParam', {editurl: delUrl});
                },
                beforeShowForm: function (e) {
                    var delUrl = baseUrl + "/fileManage/deleteFile";
                    $(grid_selector).jqGrid('setGridParam', {editurl: delUrl});
                    var form = $(e[0]);
                    if (form.data('styled')) return false;
                    form.closest('.ui-jqdialog').find('.ui-jqdialog-titlebar').wrapInner('<div class="widget-header" />')
                    style_delete_form(form);
                    form.data('styled', true);
                },
                onClick: function (e) {
                    alert(1);
                }
            },
            {
                //search form
                recreateForm: true,
                afterShowSearch: function (e) {
                    var form = $(e[0]);
                    form.closest('.ui-jqdialog').find('.ui-jqdialog-title').wrap('<div class="widget-header" />')
                    style_search_form(form);
                },
                afterRedraw: function () {
                    style_search_filters($(this));
                },
                multipleSearch: true,
            },
            {
                //view record form
                recreateForm: true,
                beforeShowForm: function (e) {
                    var form = $(e[0]);
                    form.closest('.ui-jqdialog').find('.ui-jqdialog-title').wrap('<div class="widget-header" />')
                }
            }
        )

        function beforeDeleteCallback(e) {
            var form = $(e[0]);
            if (form.data('styled')) return false;
            form.closest('.ui-jqdialog').find('.ui-jqdialog-titlebar').wrapInner('<div class="widget-header" />')
            style_delete_form(form);
            form.data('styled', true);
            var delUrl = baseUrl + "/fileManage/deleteFile";
            $(grid_selector).jqGrid('setGridParam', {editurl: delUrl});
        }

        function selectState() {
            var stateListResult = "";
            $.ajax({
                type: "get",
                async: false,
                url: baseUrl + "/apps/selectState",
                success: function (result) {
                    var result = $.parseJSON(result);
                    var stateList = result.data;
                    for (i = 0; i < stateList.length; i++) {
                        stateListResult += stateList[i].dictId + ":" + stateList[i].name + ";";
                    }
                }
            });
            if (stateListResult.length > 0) {
                stateListResult=stateListResult.substring(0,stateListResult.length-1);
            }
            return stateListResult;
        }

        function beforeEditCallback(e) {
            $("#editmodgrid-table").css("top", "20%");
            $("#editmodgrid-table").css("left", "40%");
            e.find('#appId').attr('readOnly', true);
            e.find('#appName').attr('readOnly', true);
            e.find('#version').attr('readOnly', true);
            e.find('#stateName').attr('disabled', true);
            var form = $(e[0]);
            form.closest('.ui-jqdialog').find('.ui-jqdialog-titlebar').wrapInner('<div class="widget-header" />')
            style_edit_form(form);
            var addUrl = baseUrl + "/apps";
            $(grid_selector).jqGrid('setGridParam', {editurl: addUrl});
            $("#tr_fileToUpload").css("display", "");
        }

        function afterSubmitCallback(response, postdata) {
            var res = $.parseJSON(response.responseText);
            if (res.code != 200) {
                // self.uploadFile(postdata);
                alert("提交失败，请重新提交！");
                return [false];
                // return [false, res.msg];
            } else {
                //alert("图片上传成功！");
                self.uploadFile(postdata);
                return [true];
            }
        }

        function beforeSumbitCallback() {
            var fileTypes = [".jpeg", ".png",".jpg",];
            var filePath = $('#fileToUpload').val();
            if (filePath) {
                var isNext = false;
                var fileEnd = filePath.substring(filePath.indexOf("."));
                for (var i = 0; i < fileTypes.length; i++) {
                    if (fileTypes[i] === fileEnd) {
                        isNext = true;
                        break;
                    }
                }
                if (!isNext) {
                    alert("只接受图片类型");
                    return false;
                }
                return [true];
            } else {
                alert("请选择图片！")
                return false;
            }
        }

        // function onClickSubmitCallback(params, postdata) {
        //     alert("上传成功！");
        //     self.uploadFile(postdata);
        // }

        function fmatterFuuc(cellvalue, options, rowObject) {
            if (cellvalue == 1) {
                return "应用创建";
            }
            if (cellvalue == 2) {
                return "提交审核";
            }
            if (cellvalue == 3) {
                return "审核通过";
            }
            if (cellvalue == 4) {
                return "申请灰度发布";
            }
            if (cellvalue == 5) {
                return "灰度发布";
            }
            if (cellvalue == 6) {
                return "申请上线";
            }
            if (cellvalue == 7) {
                return "上线";
            }
            if (cellvalue == 8) {
                return "申请下线";
            }
            if (cellvalue == 9) {
                return "下线";
            }
        }
    },
    uploadFile: function (postdata) {
        var formData = new FormData();
        formData.append("fileToUpload", document.getElementById("fileToUpload").files[0]);
        formData.append("appName", postdata.appName);
        formData.append("appId", postdata.appId);
//        formData.append("state",postdata.state);
//        formData.append("description",postdata.description);
        $.ajax({
            url: baseUrl + "/apps/uploadFile",
            type: "PUT",
            data: formData,
            contentType: false,
            processData: false,
            success: function (data) {
                $("#queryBtn").click();
                var data = $.parseJSON(data);
                //   console.log(">>>" + data);
                if (data.code != 200) {
                    alert(data.msg);
                } else {
                    alert("上传成功！");
                }
            },
            error: function () {
                alert("上传失败！");
            }
        });
    },
    showPicture: function (cellvalue, options, rowObject) {
        // console.log("cellvalue:"+cellvalue);
        // return "<img src='" + cellvalue + "' height='50' width='50' />";
    },
    initGirdAutoWidth: function () {
        var parent_column = $(grid_selector).closest('[class*="col-"]');
        //resize to fit page size
        $(window).on('resize.jqGrid', function () {
            $(grid_selector).jqGrid('setGridWidth', parent_column.width());
        })
        //resize on sidebar collapse/expand
        $(document).on('settings.ace.jqGrid', function (ev, event_name, collapsed) {
            if (event_name === 'sidebar_collapsed' || event_name === 'main_container_fixed') {
                //setTimeout is for webkit only to give time for DOM changes and then redraw!!!
                setTimeout(function () {
                    $(grid_selector).jqGrid('setGridWidth', parent_column.width());
                }, 20);
            }
        })
    },
    initDatePicker: function () {
        $("#timeRange").val("请选择日期");
        $('input[name=date-range-picker]').daterangepicker({
            'applyClass': 'btn-sm btn-success',
            'cancelClass': 'btn-sm btn-default',
            showDropdowns: true,//当设置值为true的时候，允许年份和月份通过下拉框的形式选择 默认false
            timePicker24Hour: true,//设置小时为24小时制 默认false
            timePicker: true,//可选中时分 默认false
            autoUpdateInput: false,//1.当设置为false的时候,不给与默认值(当前时间)2.选择时间时,失去鼠标焦点,不会给与默认值 默认true
            locale: {
                format: dateFormat,
                separator: " 至 ",
                applyLabel: '确定',
                cancelLabel: '取消',
                customRangeLabel: "自定义"
            },
            ranges: {
                '今天': [moment(), moment()],
                '昨天': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
                '近7天': [moment().subtract(7, 'days'), moment()],
                '这个月': [moment().startOf('month'), moment().endOf('month')],
                '上个月': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')]
            }
        }).on('cancel.daterangepicker', function (ev, picker) {
            $("#timeRange").val("请选择日期");
            startTime = '';
            endTime = '';
        }).on('apply.daterangepicker', function (ev, picker) {
            startTime = picker.startDate.format(dateFormat);
            endTime = picker.endDate.format(dateFormat);
            $("#timeRange").val(picker.startDate.format(dateFormat) + " 至 " + picker.endDate.format(dateFormat));
        });
    },
    init: function () {
        $(document.body).css({
            "overflow-x": "hidden"
        });
//        this.initGroup();     //查询所有组
        this.initDatePicker();  //日期函数
        this.initGirdAutoWidth(); //匹配宽度
        this.initGridData();
        this.enterEvent();
    }

}<file_sep>var baseUrl = getBaseUrl();

function getBaseUrl(){
    //获取当前网址，如： http://localhost:8083/myproj/view/my.jsp
    var curWwwPath=window.document.location.href;
    //获取主机地址之后的目录，如： myproj/view/my.jsp
    var pathName=window.document.location.pathname;
    var pos=curWwwPath.indexOf(pathName);
    //获取主机地址，如： http://localhost:8083
    var localhostPaht=curWwwPath.substring(0,pos);
    //获取带"/"的项目名，如：/myproj
    var projectName=pathName.substring(0,pathName.substr(1).indexOf('/')+1);
    //得到了 http://localhost:8083/myproj
    var realPath=localhostPaht+projectName;
    return localhostPaht;
}
Date.prototype.Format = function (fmt) { //author: meizz
    var o = {
        "M+": this.getMonth() + 1, //月份
        "d+": this.getDate(), //日
        "H+": this.getHours(), //小时
        "m+": this.getMinutes(), //分
        "s+": this.getSeconds(), //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}<file_sep>package com.azxx.picture.service;

import com.azxx.picture.entity.FileInfo;
import com.azxx.picture.entity.GroupInfo;
import com.azxx.picture.mapper.GroupInfoMapper;
import com.azxx.picture.vo.groupInfo.GroupReqVo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * @version V1.0
 * @class: GroupService
 * @description: group service
 * @author: xuzheng
 * @create: 2019-02-02 10:15
 **/
@Service
public class GroupService {
    private static final Logger logger = LoggerFactory.getLogger(GroupService.class);

    @Autowired
    private GroupInfoMapper groupInfoMapper;

    public List<GroupInfo> getGroups(GroupReqVo reqVo){
        List<GroupInfo> result = null;
        if(reqVo == null){
            return result;
        }
        GroupInfo groupInfo = new GroupInfo();
        BeanUtils.copyProperties(reqVo,groupInfo);
        return groupInfoMapper.select(groupInfo);
    }

    public PageInfo<GroupInfo> pages(GroupReqVo reqVo){
        GroupInfo groupInfo = new GroupInfo();
        BeanUtils.copyProperties(reqVo,groupInfo);
        return PageHelper.startPage(reqVo.getPage(), reqVo.getRows()).doSelectPageInfo(() -> groupInfoMapper.select(groupInfo));
    }

    public boolean addOrUpdateGroup(GroupReqVo reqVo){
        int effectRows = 0;
        if(reqVo == null) {
            return false;
        }
        GroupInfo groupInfo = new GroupInfo();
        BeanUtils.copyProperties(reqVo,groupInfo);
        groupInfo.setRecordTime(new Date());
        if(reqVo.getId()==null || reqVo.getId() == 0){
            effectRows = groupInfoMapper.insert(groupInfo);
        }else{
            effectRows = groupInfoMapper.updateByPrimaryKeySelective(groupInfo);
        }
        return effectRows>0?true:false;
    }

    public boolean deleteGroup(Integer id){
        int effectRows = 0;
        if(id == null) {
            return false;
        }
        effectRows = groupInfoMapper.deleteByPrimaryKey(id);
        return effectRows>0?true:false;
    }
}
<file_sep>package com.azxx.picture.controller;

import com.alibaba.fastjson.JSON;
import com.azxx.picture.vo.BaseResult;
import com.azxx.picture.vo.OperateTypeEm;
import com.azxx.picture.vo.ResultCodeEm;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @version V1.0
 * @class: BaseController
 * @description: base controller
 * @author: xuzheng
 * @create: 2019-02-02 11:16
 **/
public class BaseController {

    private static final Logger logger = LoggerFactory.getLogger(BaseController.class);

    /**
     * 返回结果
     * @param object 返回对象
     * @param operateType 操作类型
     * @return
     */
    public String ok(Object object,String operateType){
        BaseResult result = new BaseResult();
        if(StringUtils.isBlank(operateType)){
            operateType = OperateTypeEm.QUERY.toString();
        }
        if(operateType.equals(OperateTypeEm.QUERY.toString())){
            result.setCode(ResultCodeEm.QUERY_SUCCESS.getCode());
            result.setMsg(ResultCodeEm.QUERY_SUCCESS.getMsg());
        }else if(operateType.equals(OperateTypeEm.UPDATE.toString())){
            result.setCode(ResultCodeEm.UPDATE_SUCCESS.getCode());
            result.setMsg(ResultCodeEm.UPDATE_SUCCESS.getMsg());
        }else if(operateType.equals(OperateTypeEm.DELETE.toString())){
            result.setCode(ResultCodeEm.DELETE_SUCCESS.getCode());
            result.setMsg(ResultCodeEm.DELETE_SUCCESS.getMsg());
        }
        result.setData(object);
        return JSON.toJSONString(result);
    }

    public String queryOk(Object object){
        BaseResult result = new BaseResult();
        result.setCode(ResultCodeEm.QUERY_SUCCESS.getCode());
        result.setMsg(ResultCodeEm.QUERY_SUCCESS.getMsg());
        result.setData(object);
        return JSON.toJSONString(result);
    }

    public String updateOk(Object object){
        BaseResult result = new BaseResult();
        result.setCode(ResultCodeEm.UPDATE_SUCCESS.getCode());
        result.setMsg(ResultCodeEm.UPDATE_SUCCESS.getMsg());
        result.setData(object);
        return JSON.toJSONString(result);
    }

    public String ok(Object object,String code,String msg){
        BaseResult result = new BaseResult();
        result.setCode(code);
        result.setMsg(msg);
        result.setData(object);
        return JSON.toJSONString(result);
    }

    public String paramsError(){
        BaseResult result = new BaseResult();
        result.setCode(ResultCodeEm.PARAMS_ERROR.getCode());
        result.setMsg(ResultCodeEm.PARAMS_ERROR.getMsg());
        return JSON.toJSONString(result);
    }

    /**
     *
     * @param object
     * @param operateType
     * @return
     */
    public String error(Object object,String operateType){
        BaseResult result = new BaseResult();
        if(StringUtils.isBlank(operateType)){
            operateType = OperateTypeEm.QUERY.toString();
        }
        if(operateType.equals(OperateTypeEm.QUERY.toString())){
            result.setCode(ResultCodeEm.QUERY_FIALURE.getCode());
            result.setMsg(ResultCodeEm.QUERY_FIALURE.getMsg());
        }else if(operateType.equals(OperateTypeEm.UPDATE.toString())){
            result.setCode(ResultCodeEm.UPDATE_FIALURE.getCode());
            result.setMsg(ResultCodeEm.UPDATE_FIALURE.getMsg());
        }else if(operateType.equals(OperateTypeEm.DELETE.toString())){
            result.setCode(ResultCodeEm.DELETE_FIALURE.getCode());
            result.setMsg(ResultCodeEm.DELETE_FIALURE.getMsg());
        }
        result.setData(object);
        return JSON.toJSONString(result);
    }



}
<file_sep>package com.azxx.picture.vo.groupInfo;

import io.swagger.annotations.ApiModelProperty;

/**
 * @version V1.0
 * @class: GroupReqVo
 * @description: group request vo
 * @author: xuzheng
 * @create: 2019-02-02 10:44
 **/
public class GroupReqVo {

    @ApiModelProperty(value = "分组描述",dataType = "string")
    private String description;

    @ApiModelProperty(value = "分组名称",dataType = "string")
    private String name;

    @ApiModelProperty(value = "ID",dataType = "int")
    private Integer id;

    private Integer page;

    private Integer rows;

    public Integer getPage() {
        return page;
    }

    public void setPage(Integer page) {
        this.page = page;
    }

    public Integer getRows() {
        return rows;
    }

    public void setRows(Integer rows) {
        this.rows = rows;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}
