SpringBoot文件上传和下载
来源:互联网 发布:java随机生成小写字母 编辑:程序博客网 时间:2024/05/17 06:07
Controller:
@RestController@Api(value = "文件上传下载相关接口")@RequestMapping(value = "/file", produces = "application/json;charset=utf-8")public class FileController { private static final Logger log = LoggerFactory.getLogger(FileController.class); @ApiOperation("单文件上传") @PostMapping public JsonResult<Void> fileUpload(MultipartFile file) throws IOException { if (null == file) { log.error("上传文件不能为空"); return new JsonResult<>("4", "上传文件不能为空!"); } String fileName = file.getOriginalFilename(); byte[] bytes = file.getBytes(); log.info("开始上传文件【{}】...", fileName); FileUtils.writeByteArrayToFile(new File("d:/" + fileName), bytes); log.info("文件【{}】上传成功...", fileName); return new JsonResult<>(); } @ApiOperation("多文件上传") @PostMapping("/batch") public JsonResult<Void> batchFileUpload(HttpServletRequest request) throws IOException { List<MultipartFile> fileList = ((MultipartHttpServletRequest) request).getFiles("file"); for (int i = 0; i < fileList.size(); i++) { MultipartFile file = fileList.get(i); byte[] bytes = file.getBytes(); log.info("开始上传文件【{}】...", i); FileUtils.writeByteArrayToFile(new File("d:/temp" + file.getOriginalFilename()), bytes); log.info("文件【{}】上传成功...", i); } return new JsonResult<>(); } @ApiOperation("文件下载") @GetMapping("/download") public JsonResult<Void> download(HttpServletResponse response) throws UnsupportedEncodingException { String fileName = "干净桌面.jpg"; // 设置强制下载不打开 response.setContentType("application/force-download"); response.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("utf-8"),"ISO-8859-1"));// byte[] buff = new byte[1024]; BufferedInputStream bis = null; try { ServletOutputStream outputStream = response.getOutputStream(); byte[] buff = FileUtils.readFileToByteArray(new File("C:\\Users\\Administrator\\Pictures\\电脑桌面\\" + fileName)); outputStream.write(buff); } catch (IOException e) { e.printStackTrace(); } return new JsonResult<>(); }}
Freemarker:
<!doctype html><html lang="zh-cn"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>File</title></head><body> <p>Get your greeting <a href="/greeting">here</a></p> <form action="/upload" method="POST" enctype="multipart/form-data"> 文件:<input type="file" name="test"/> <input type="submit"/> </form> <a href="/file/download">下载test</a> <p>多文件上传</p> <form method="POST" enctype="multipart/form-data" action="/file/batch"> <p>文件1:<input type="file" name="file"/></p> <p>文件2:<input type="file" name="file"/></p> <p><input type="submit" value="上传"/></p> </form></body></html>
配置文件application.yml:
#设置激活的环境 devspring: profiles: active: dev#------------------------------------------------------------------------------------------ datasource: name: test url: jdbc:mysql://127.0.0.1:3306/mytest?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull username: root password: 123456 # 使用druid数据源 type: com.alibaba.druid.pool.DruidDataSource driver-class-name: com.mysql.jdbc.Driver druid: initial-size: 1 min-idle: 20 max-active: 300 test-on-borrow: true#freemarker freemarker: template-loader-path: classpath:/templates #设置禁用模板引擎缓存 cache: false settings: template_update_delay: 0#静态文件 mvc: static-path-pattern: /static/**#文件上传设置 http: multipart: max-file-size: 100MB max-request-size: 100MB#devtools devtools: restart: enabled: true#pagehelper分页插件pagehelper: helperDialect: mysql reasonable: true supportMethodsArguments: true params: count=countSql#jar外部配置logback.xmllogging: config: logback.xmlmybatis: type-aliases-package: com.iflytek.icourt.model mapper-locations: classpath:mapping/*.xml
pom.xml文件:
<?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> <groupId>com.iflytek</groupId> <artifactId>sm-admin</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>sm-admin</name> <description>Spring Boot Mybatis integration</description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.9.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-freemarker</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.35</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <!--springBoot MyBatis 及 插件依赖 --> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.3.1</version> </dependency> <!--阿里 Druid Spring Boot Starter依赖 --> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid-spring-boot-starter</artifactId> <version>1.1.4</version> </dependency> <!-- 公共MyBatis mapper --> <dependency> <groupId>tk.mybatis</groupId> <artifactId>mapper-spring-boot-starter</artifactId> <version>1.1.4</version> </dependency> <dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper-spring-boot-starter</artifactId> <version>1.2.1</version> </dependency> <!--阿里 FastJson依赖 --> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.38</version> </dependency> <!--阿里 Druid Spring Boot Starter依赖 --> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid-spring-boot-starter</artifactId> <version>1.1.4</version> </dependency> <!-- Swagger相关 start --> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.2.2</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.2.2</version> </dependency> <!-- 自定义配置 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-configuration-processor</artifactId> <optional>true</optional> </dependency> <!-- commons-io --> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.5</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> <!-- mybatis generator 自动生成代码插件 --> <plugin> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-maven-plugin</artifactId> <version>1.3.2</version> <configuration> <configurationFile>${basedir}/src/main/resources/generator/generatorConfig.xml</configurationFile> <overwrite>true</overwrite> <verbose>true</verbose> </configuration> </plugin> </plugins> </build></project>
阅读全文