博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
SpringBoot | 第二章:配置多环境以及上传文件
阅读量:4180 次
发布时间:2019-05-26

本文共 12096 字,大约阅读时间需要 40 分钟。

一、创建个Springboot工程pom.xml配置如下:

4.0.0
com.example
chapter
0.0.1-SNAPSHOT
jar
chapter
Demo project for Spring Boot
org.springframework.boot
spring-boot-starter-parent
2.1.0.RELEASE
UTF-8
UTF-8
1.8
org.springframework.boot
spring-boot-starter-web
org.springframework.boot
spring-boot-starter-test
test
mysql
mysql-connector-java
5.1.34
org.projectlombok
lombok
1.16.10
org.springframework.boot
spring-boot-devtools
true
org.mybatis.spring.boot
mybatis-spring-boot-starter
1.3.1
org.springframework.boot
spring-boot-starter-freemarker
2.0.2.RELEASE
org.springframework.boot
spring-boot-starter-thymeleaf
com.alibaba
fastjson
1.2.32
org.springframework.boot
spring-boot-maven-plugin

二、application.properties配置如下:

# 默认的 8080 我们将它改成 9090# server.port=9090# 未定义上下文路径之前 地址是 http://localhost:8080 定义了后 http://localhost:9090/chapter1 你能在tomcat做的事情,配置文件都可以#server.servlet.context-path=/chapter1spring.profiles.active=test# mysqlspring.datasource.url=jdbc:mysql://localhost:3306/springbootdemo?characterEncoding=UTF-8spring.datasource.username=rootspring.datasource.password=113506spring.datasource.driver-class-name=com.mysql.jdbc.Driver#springboot自带的iconspring.mvc.favicon.enabled=false#热部署生效spring.devtools.restart.enabled=true#Ctrl+Shift+F9 重新加载spring.thymeleaf.cache=false#freemarker热部署spring.freemarker.cache=falsespring.freemarker.settings.template_update_delay=0#==================== 日志配合·标准  ============================logging.config=classpath:logback-spring.xml#设定ftl文件路径spring.freemarker.template-loader-path=classpath:/templates#设定静态文件路径,js,css等  访问时需要加/staticspring.mvc.static-path-pattern=/static/**spring.mvc.servlet.path=#==========================测试可以 改成true 会自动启动================spring.auto.openurl=truespring.web.loginurl=http://localhost:${server.port}/upload/toUploadspring.web.googleexcute=C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe#=====================文件上传======================================# 是否支持批量上传   (默认值 true)spring.servlet.multipart.enabled=true# 上传文件的临时目录 (一般情况下不用特意修改)spring.servlet.multipart.location=# 上传文件最大为 1M (默认值 1M 根据自身业务自行控制即可)spring.servlet.multipart.max-file-size=10MB# 上传请求最大为 10M(默认值10M 根据自身业务自行控制即可)spring.servlet.multipart.max-request-size=20MB# 文件大小阈值,当大于这个阈值时将写入到磁盘,否则存在内存中,(默认值0 一般情况下不用特意修改)spring.servlet.multipart.file-size-threshold=0# 判断是否要延迟解析文件(相当于懒加载,一般情况下不用特意修改)spring.servlet.multipart.resolve-lazily=false

三、多环境配置:

3.1、application-dev.properties配置:

#默认是server.servlet.context-path=/#server.servlet.context-path=/devserver.port=8070

3.2、application-test.properties配置:

#默认是server.servlet.context-path=/#server.servlet.context-path=/testserver.port=8092

3.3、application-prod.properties配置:

#默认是server.servlet.context-path=/#server.servlet.context-path=/prodserver.port=8080

四、配置项目启动默认打开的页面:

package com.example.common;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.beans.factory.annotation.Value;import org.springframework.boot.CommandLineRunner;import org.springframework.stereotype.Component;/** * 设置运行项目默认打开的界面 * @author tanhw119214  on  2018/6/14 14:41 */@Componentpublic class MyCommandRunner implements CommandLineRunner {    private static Logger logger = LoggerFactory.getLogger(MyCommandRunner.class);    @Value("${spring.web.loginurl}")    private String loginUrl;    @Value("${spring.web.googleexcute}")    private String googleExcutePath;    @Value("${spring.auto.openurl}")    private boolean isOpen;    @Override    public void run(String... args) throws Exception {        if(isOpen){            String cmd = googleExcutePath +" "+ loginUrl;            Runtime run = Runtime.getRuntime();            try{                run.exec(cmd);                logger.debug("启动浏览器打开项目成功");            }catch (Exception e){                e.printStackTrace();                logger.error(e.getMessage());            }        }    }}

五、控制器定义如下:

package com.example.controller;import com.alibaba.fastjson.JSON;import com.alibaba.fastjson.JSONArray;import lombok.extern.slf4j.Slf4j;import org.springframework.beans.factory.annotation.Value;import org.springframework.stereotype.Controller;import org.springframework.ui.Model;import org.springframework.util.Base64Utils;import org.springframework.util.ClassUtils;import org.springframework.util.FileCopyUtils;import org.springframework.web.bind.annotation.*;import org.springframework.web.multipart.MultipartFile;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import java.io.*;import java.util.*;/** * @author xiaobu * @version JDK1.8.0_171 * @date on  2018/11/14 9:40 * @description V1.0 文件上传控制器  @RequestMapping("${server.servlet.context-path}/upload") 等价于 * http://localhost:8092/test/test/upload/toUpload * 若设置了server.servlet.context-path=/test * 控制器也不需要加${server.servlet.context-path=/test} * springboot 默认追加了。 */@RequestMapping("/upload")@Controller@Slf4jpublic class UploadController {   /* @Value("${server.servlet.context-path}")    protected String adminPath;*/    /**     * @return java.lang.String     * @author xiaobu     * @date 2018/11/14 10:23     * @descprition 进入上传页面     * @version 1.0     */    @GetMapping("/toUpload")    public String toUpload(Model model) {        return "/upload";    }    /**     * @param file, request     * @return java.util.Map
* @author xiaobu * @date 2018/11/14 11:38 * @descprition 上传单个文件 * @version 1.0 */ @PostMapping("/upload1") @ResponseBody public Map
upload1(@RequestParam("file") MultipartFile file, HttpServletRequest request) { //获取项目的路径 String uploadDir = Objects.requireNonNull(Objects.requireNonNull(ClassUtils.getDefaultClassLoader()).getResource("")).getPath(); System.out.println("uploadDir:" + uploadDir); uploadDir = uploadDir.substring(1); String path = "static/upload/"; String filepath = uploadDir + path; System.out.println("uploadDir ==========" + uploadDir); log.info("[文件大小]:=============" + file.getSize()); log.info("[文件名称]:=============" + file.getOriginalFilename()); log.info("[文件类型]:=============" + file.getContentType()); try { file.transferTo(new File(filepath + file.getOriginalFilename())); } catch (IOException e) { e.printStackTrace(); } Map
map = new HashMap<>(); map.put("文件大小", file.getSize() + ""); map.put("文件名称", file.getOriginalFilename()); map.put("文件类型", file.getContentType()); return map; } /** * @param files 上传的文件 * @return java.lang.String * @author xiaobu * @date 2018/11/14 11:38 * @descprition 上传多个文件 * @version 1.0 */ @PostMapping("/upload2") @ResponseBody public String upload2(@RequestParam("file") MultipartFile[] files) { String sep = System.getProperty("file.separator"); String uploadDir = Objects.requireNonNull(Objects.requireNonNull(ClassUtils.getDefaultClassLoader()).getResource("")).getPath(); System.out.println("uploadDir:" + uploadDir); uploadDir = uploadDir.substring(1); String path = "static/upload/"; String filepath = uploadDir + path; System.out.println("static" + sep + "upload"); List
> list = new ArrayList<>(); for (MultipartFile file : files) { log.info("[文件大小]:=============" + file.getSize()); log.info("[文件名称]:=============" + file.getOriginalFilename()); log.info("[文件类型]:=============" + file.getContentType()); try { file.transferTo(new File(filepath + file.getOriginalFilename())); } catch (IOException e) { e.printStackTrace(); } Map
map = new HashMap<>(); map.put("文件大小", file.getSize() + ""); map.put("文件名称", file.getOriginalFilename()); map.put("文件类型", file.getContentType()); list.add(map); } //JSON.toJSONString(list) 把list转换成String //JSONArray.parseArray(String) 把String转成JSONArray JSONArray jsonArray = JSONArray.parseArray(JSON.toJSONString(list)); return jsonArray.toString(); } /** * @param base64 base64字符串 * @author xiaobu * @date 2018/11/14 11:36 * @descprition base64转图片 * @version 1.0 */ @PostMapping("/upload3") @ResponseBody public String upload3(String base64) { System.out.println("base64的长度==========>>" + base64.length()); String uploadDir = Objects.requireNonNull(Objects.requireNonNull(ClassUtils.getDefaultClassLoader()).getResource("")).getPath(); System.out.println("uploadDir:" + uploadDir); uploadDir = uploadDir.substring(1); String path = "static/upload/"; String filepath = uploadDir + path; // TODO BASE64 方式的 格式和名字需要自己控制(如 png 图片编码后前缀就会是 data:image/png;base64,) final File tempFile = new File(filepath + "test.jpg"); // TODO 防止有的传了 data:image/png;base64, 有的没传的情况 String[] d = base64.split("base64,"); final byte[] bytes = Base64Utils.decodeFromString(d.length > 1 ? d[1] : d[0]); try { FileCopyUtils.copy(bytes, tempFile); } catch (IOException e) { e.printStackTrace(); } return "图片上传成功!"; } /** * 下载 * * @param res */ @RequestMapping(value = "/download", method = RequestMethod.GET) public void download(HttpServletResponse res, HttpServletRequest request) { String downLoadDir = Objects.requireNonNull(Objects.requireNonNull(ClassUtils.getDefaultClassLoader()).getResource("")).getPath(); System.out.println("downLoadDir:" + downLoadDir); downLoadDir = downLoadDir.substring(1); String path = "static/img/"; String downLoadPath = downLoadDir + path; String fileName = "777.png"; res.setHeader("content-type", "application/octet-stream"); res.setContentType("application/octet-stream"); res.setHeader("Content-Disposition", "attachment;filename=" + fileName); byte[] buff = new byte[1024]; BufferedInputStream bis = null; OutputStream os = null; try { os = res.getOutputStream(); bis = new BufferedInputStream(new FileInputStream(new File(downLoadPath + fileName))); int i = bis.read(buff); while (i != -1) { os.write(buff, 0, buff.length); os.flush(); i = bis.read(buff); } } catch (IOException e) { e.printStackTrace(); } finally { if (bis != null) { try { bis.close(); } catch (IOException e) { e.printStackTrace(); } } } System.out.println("success"); }}

六、前端上传页面:

    
文件上传

单一文件上传示例

文件1:


批量文件上传示例

文件1:

文件2:


Base64文件上传

BASE64编码:

 

转载地址:http://yygai.baihongyu.com/

你可能感兴趣的文章
利用多线程(用到原子类AtomicInteger)往数据库批量插入大量数据
查看>>
多个线程操作数组
查看>>
定长线程池的应用
查看>>
ArrayBlockingQueue的简单使用
查看>>
Git 常用命令总结(一)
查看>>
Git 常用命令总结(二)
查看>>
JAVA 并发——synchronized的分析
查看>>
Echarts——使用 dataset 管理数据
查看>>
DES 加解密工具类
查看>>
SpringBoot多模块项目实践(Multi-Module)
查看>>
第一篇: 服务的注册与发现Eureka(Greenwich版)
查看>>
第二篇: 服务消费者(rest+ribbon)(Greenwich版本)
查看>>
第三篇: 服务消费者(Feign)(Greenwich版本)
查看>>
获取客户的真实IP地址
查看>>
第四篇: 熔断器(Ribbon+Feign)(Greenwich版本)
查看>>
Linux的常用命令(一)
查看>>
Linux的常用命令(二)
查看>>
第六篇: 分布式配置中心(Greenwich版本)
查看>>
SpringBoot | 配置logback-spring.xml
查看>>
SpringBoot | 第一章:构建第一个SpringBoot工程
查看>>