本文共 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
六、前端上传页面:
文件上传 单一文件上传示例
批量文件上传示例
Base64文件上传
转载地址:http://yygai.baihongyu.com/